2 #include "frameobject.h"
4 #define MODULE_NAME "_warnings"
6 PyDoc_STRVAR(warnings__doc__
,
7 MODULE_NAME
" provides basic warning filtering support.\n"
8 "It is a helper module to speed up interpreter start-up.");
10 /* Both 'filters' and 'onceregistry' can be set in warnings.py;
11 get_warnings_attr() will reset these variables accordingly. */
12 static PyObject
*_filters
; /* List */
13 static PyObject
*_once_registry
; /* Dict */
14 static PyObject
*_default_action
; /* String */
18 check_matched(PyObject
*obj
, PyObject
*arg
)
25 result
= PyObject_CallMethod(obj
, "match", "O", arg
);
29 rc
= PyObject_IsTrue(result
);
35 Returns a new reference.
36 A NULL return value can mean false or an error.
39 get_warnings_attr(const char *attr
)
41 static PyObject
*warnings_str
= NULL
;
42 PyObject
*all_modules
;
43 PyObject
*warnings_module
;
46 if (warnings_str
== NULL
) {
47 warnings_str
= PyString_InternFromString("warnings");
48 if (warnings_str
== NULL
)
52 all_modules
= PyImport_GetModuleDict();
53 result
= PyDict_Contains(all_modules
, warnings_str
);
54 if (result
== -1 || result
== 0)
57 warnings_module
= PyDict_GetItem(all_modules
, warnings_str
);
58 if (!PyObject_HasAttrString(warnings_module
, attr
))
60 return PyObject_GetAttrString(warnings_module
, attr
);
65 get_once_registry(void)
69 registry
= get_warnings_attr("onceregistry");
70 if (registry
== NULL
) {
73 return _once_registry
;
75 Py_DECREF(_once_registry
);
76 _once_registry
= registry
;
82 get_default_action(void)
84 PyObject
*default_action
;
86 default_action
= get_warnings_attr("defaultaction");
87 if (default_action
== NULL
) {
88 if (PyErr_Occurred()) {
91 return _default_action
;
94 Py_DECREF(_default_action
);
95 _default_action
= default_action
;
96 return default_action
;
100 /* The item is a borrowed reference. */
102 get_filter(PyObject
*category
, PyObject
*text
, Py_ssize_t lineno
,
103 PyObject
*module
, PyObject
**item
)
107 PyObject
*warnings_filters
;
109 warnings_filters
= get_warnings_attr("filters");
110 if (warnings_filters
== NULL
) {
111 if (PyErr_Occurred())
116 _filters
= warnings_filters
;
119 if (!PyList_Check(_filters
)) {
120 PyErr_SetString(PyExc_ValueError
,
121 MODULE_NAME
".filters must be a list");
125 /* _filters could change while we are iterating over it. */
126 for (i
= 0; i
< PyList_GET_SIZE(_filters
); i
++) {
127 PyObject
*tmp_item
, *action
, *msg
, *cat
, *mod
, *ln_obj
;
129 int is_subclass
, good_msg
, good_mod
;
131 tmp_item
= *item
= PyList_GET_ITEM(_filters
, i
);
132 if (PyTuple_Size(tmp_item
) != 5) {
133 PyErr_Format(PyExc_ValueError
,
134 MODULE_NAME
".filters item %zd isn't a 5-tuple", i
);
138 /* Python code: action, msg, cat, mod, ln = item */
139 action
= PyTuple_GET_ITEM(tmp_item
, 0);
140 msg
= PyTuple_GET_ITEM(tmp_item
, 1);
141 cat
= PyTuple_GET_ITEM(tmp_item
, 2);
142 mod
= PyTuple_GET_ITEM(tmp_item
, 3);
143 ln_obj
= PyTuple_GET_ITEM(tmp_item
, 4);
145 good_msg
= check_matched(msg
, text
);
146 good_mod
= check_matched(mod
, module
);
147 is_subclass
= PyObject_IsSubclass(category
, cat
);
148 ln
= PyInt_AsSsize_t(ln_obj
);
149 if (good_msg
== -1 || good_mod
== -1 || is_subclass
== -1 ||
150 (ln
== -1 && PyErr_Occurred()))
153 if (good_msg
&& is_subclass
&& good_mod
&& (ln
== 0 || lineno
== ln
))
154 return PyString_AsString(action
);
157 action
= get_default_action();
158 if (action
!= NULL
) {
159 return PyString_AsString(action
);
162 PyErr_SetString(PyExc_ValueError
,
163 MODULE_NAME
".defaultaction not found");
169 already_warned(PyObject
*registry
, PyObject
*key
, int should_set
)
171 PyObject
*already_warned
;
176 already_warned
= PyDict_GetItem(registry
, key
);
177 if (already_warned
!= NULL
) {
178 int rc
= PyObject_IsTrue(already_warned
);
183 /* This warning wasn't found in the registry, set it. */
185 return PyDict_SetItem(registry
, key
, Py_True
);
191 normalize_module(PyObject
*filename
)
197 int rc
= PyObject_IsTrue(filename
);
201 return PyString_FromString("<unknown>");
203 mod_str
= PyString_AsString(filename
);
206 len
= PyString_Size(filename
);
210 strncmp(mod_str
+ (len
- 3), ".py", 3) == 0) {
211 module
= PyString_FromStringAndSize(mod_str
, len
-3);
221 update_registry(PyObject
*registry
, PyObject
*text
, PyObject
*category
,
224 PyObject
*altkey
, *zero
= NULL
;
228 zero
= PyInt_FromLong(0);
231 altkey
= PyTuple_Pack(3, text
, category
, zero
);
234 altkey
= PyTuple_Pack(2, text
, category
);
236 rc
= already_warned(registry
, altkey
, 1);
243 show_warning(PyObject
*filename
, int lineno
, PyObject
*text
, PyObject
244 *category
, PyObject
*sourceline
)
248 char lineno_str
[128];
250 PyOS_snprintf(lineno_str
, sizeof(lineno_str
), ":%d: ", lineno
);
252 name
= PyObject_GetAttrString(category
, "__name__");
253 if (name
== NULL
) /* XXX Can an object lack a '__name__' attribute? */
256 f_stderr
= PySys_GetObject("stderr");
257 if (f_stderr
== NULL
) {
258 fprintf(stderr
, "lost sys.stderr\n");
263 /* Print "filename:lineno: category: text\n" */
264 PyFile_WriteObject(filename
, f_stderr
, Py_PRINT_RAW
);
265 PyFile_WriteString(lineno_str
, f_stderr
);
266 PyFile_WriteObject(name
, f_stderr
, Py_PRINT_RAW
);
267 PyFile_WriteString(": ", f_stderr
);
268 PyFile_WriteObject(text
, f_stderr
, Py_PRINT_RAW
);
269 PyFile_WriteString("\n", f_stderr
);
272 /* Print " source_line\n" */
274 char *source_line_str
= PyString_AS_STRING(sourceline
);
275 while (*source_line_str
== ' ' || *source_line_str
== '\t' ||
276 *source_line_str
== '\014')
279 PyFile_WriteString(source_line_str
, f_stderr
);
280 PyFile_WriteString("\n", f_stderr
);
283 _Py_DisplaySourceLine(f_stderr
, PyString_AS_STRING(filename
),
289 warn_explicit(PyObject
*category
, PyObject
*message
,
290 PyObject
*filename
, int lineno
,
291 PyObject
*module
, PyObject
*registry
, PyObject
*sourceline
)
293 PyObject
*key
= NULL
, *text
= NULL
, *result
= NULL
, *lineno_obj
= NULL
;
294 PyObject
*item
= Py_None
;
298 if (registry
&& !PyDict_Check(registry
) && (registry
!= Py_None
)) {
299 PyErr_SetString(PyExc_TypeError
, "'registry' must be a dict");
303 /* Normalize module. */
304 if (module
== NULL
) {
305 module
= normalize_module(filename
);
312 /* Normalize message. */
313 Py_INCREF(message
); /* DECREF'ed in cleanup. */
314 rc
= PyObject_IsInstance(message
, PyExc_Warning
);
319 text
= PyObject_Str(message
);
322 category
= (PyObject
*)message
->ob_type
;
326 message
= PyObject_CallFunction(category
, "O", message
);
331 lineno_obj
= PyInt_FromLong(lineno
);
332 if (lineno_obj
== NULL
)
336 key
= PyTuple_Pack(3, text
, category
, lineno_obj
);
340 if ((registry
!= NULL
) && (registry
!= Py_None
)) {
341 rc
= already_warned(registry
, key
, 0);
346 /* Else this warning hasn't been generated before. */
349 action
= get_filter(category
, text
, lineno
, module
, &item
);
353 if (strcmp(action
, "error") == 0) {
354 PyErr_SetObject(category
, message
);
358 /* Store in the registry that we've been here, *except* when the action
361 if (strcmp(action
, "always") != 0) {
362 if (registry
!= NULL
&& registry
!= Py_None
&&
363 PyDict_SetItem(registry
, key
, Py_True
) < 0)
365 else if (strcmp(action
, "ignore") == 0)
367 else if (strcmp(action
, "once") == 0) {
368 if (registry
== NULL
|| registry
== Py_None
) {
369 registry
= get_once_registry();
370 if (registry
== NULL
)
373 /* _once_registry[(text, category)] = 1 */
374 rc
= update_registry(registry
, text
, category
, 0);
376 else if (strcmp(action
, "module") == 0) {
377 /* registry[(text, category, 0)] = 1 */
378 if (registry
!= NULL
&& registry
!= Py_None
)
379 rc
= update_registry(registry
, text
, category
, 0);
381 else if (strcmp(action
, "default") != 0) {
382 PyObject
*to_str
= PyObject_Str(item
);
383 const char *err_str
= "???";
386 err_str
= PyString_AS_STRING(to_str
);
387 PyErr_Format(PyExc_RuntimeError
,
388 "Unrecognized action (%s) in warnings.filters:\n %s",
395 if (rc
== 1) /* Already warned for this module. */
398 PyObject
*show_fxn
= get_warnings_attr("showwarning");
399 if (show_fxn
== NULL
) {
400 if (PyErr_Occurred())
402 show_warning(filename
, lineno
, text
, category
, sourceline
);
407 if (!PyMethod_Check(show_fxn
) && !PyFunction_Check(show_fxn
)) {
408 PyErr_SetString(PyExc_TypeError
,
409 "warnings.showwarning() must be set to a "
410 "function or method");
415 res
= PyObject_CallFunctionObjArgs(show_fxn
, message
, category
,
416 filename
, lineno_obj
,
424 else /* if (rc == -1) */
434 Py_XDECREF(lineno_obj
);
437 return result
; /* Py_None or NULL. */
440 /* filename, module, and registry are new refs, globals is borrowed */
441 /* Returns 0 on error (no new refs), 1 on success */
443 setup_context(Py_ssize_t stack_level
, PyObject
**filename
, int *lineno
,
444 PyObject
**module
, PyObject
**registry
)
448 /* Setup globals and lineno. */
449 PyFrameObject
*f
= PyThreadState_GET()->frame
;
450 while (--stack_level
> 0 && f
!= NULL
)
454 globals
= PyThreadState_Get()->interp
->sysdict
;
458 globals
= f
->f_globals
;
459 *lineno
= PyFrame_GetLineNumber(f
);
464 /* Setup registry. */
465 assert(globals
!= NULL
);
466 assert(PyDict_Check(globals
));
467 *registry
= PyDict_GetItemString(globals
, "__warningregistry__");
468 if (*registry
== NULL
) {
471 *registry
= PyDict_New();
472 if (*registry
== NULL
)
475 rc
= PyDict_SetItemString(globals
, "__warningregistry__", *registry
);
480 Py_INCREF(*registry
);
483 *module
= PyDict_GetItemString(globals
, "__name__");
484 if (*module
== NULL
) {
485 *module
= PyString_FromString("<string>");
492 /* Setup filename. */
493 *filename
= PyDict_GetItemString(globals
, "__file__");
494 if (*filename
!= NULL
) {
495 Py_ssize_t len
= PyString_Size(*filename
);
496 const char *file_str
= PyString_AsString(*filename
);
497 if (file_str
== NULL
|| (len
< 0 && PyErr_Occurred()))
500 /* if filename.lower().endswith((".pyc", ".pyo")): */
502 file_str
[len
-4] == '.' &&
503 tolower(file_str
[len
-3]) == 'p' &&
504 tolower(file_str
[len
-2]) == 'y' &&
505 (tolower(file_str
[len
-1]) == 'c' ||
506 tolower(file_str
[len
-1]) == 'o'))
508 *filename
= PyString_FromStringAndSize(file_str
, len
-1);
509 if (*filename
== NULL
)
513 Py_INCREF(*filename
);
516 const char *module_str
= PyString_AsString(*module
);
517 if (module_str
&& strcmp(module_str
, "__main__") == 0) {
518 PyObject
*argv
= PySys_GetObject("argv");
519 if (argv
!= NULL
&& PyList_Size(argv
) > 0) {
521 *filename
= PyList_GetItem(argv
, 0);
522 Py_INCREF(*filename
);
523 /* If sys.argv[0] is false, then use '__main__'. */
524 is_true
= PyObject_IsTrue(*filename
);
526 Py_DECREF(*filename
);
530 Py_DECREF(*filename
);
531 *filename
= PyString_FromString("__main__");
532 if (*filename
== NULL
)
537 /* embedded interpreters don't have sys.argv, see bug #839151 */
538 *filename
= PyString_FromString("__main__");
539 if (*filename
== NULL
)
543 if (*filename
== NULL
) {
545 Py_INCREF(*filename
);
552 /* filename not XDECREF'ed here as there is no way to jump here with a
553 dangling reference. */
554 Py_XDECREF(*registry
);
560 get_category(PyObject
*message
, PyObject
*category
)
565 rc
= PyObject_IsInstance(message
, PyExc_Warning
);
570 category
= (PyObject
*)message
->ob_type
;
571 else if (category
== NULL
)
572 category
= PyExc_UserWarning
;
574 /* Validate category. */
575 rc
= PyObject_IsSubclass(category
, PyExc_Warning
);
579 PyErr_SetString(PyExc_ValueError
,
580 "category is not a subclass of Warning");
588 do_warn(PyObject
*message
, PyObject
*category
, Py_ssize_t stack_level
)
590 PyObject
*filename
, *module
, *registry
, *res
;
593 if (!setup_context(stack_level
, &filename
, &lineno
, &module
, ®istry
))
596 res
= warn_explicit(category
, message
, filename
, lineno
, module
, registry
,
605 warnings_warn(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
607 static char *kw_list
[] = { "message", "category", "stacklevel", 0 };
608 PyObject
*message
, *category
= NULL
;
609 Py_ssize_t stack_level
= 1;
611 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|On:warn", kw_list
,
612 &message
, &category
, &stack_level
))
615 category
= get_category(message
, category
);
616 if (category
== NULL
)
618 return do_warn(message
, category
, stack_level
);
622 warnings_warn_explicit(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
624 static char *kwd_list
[] = {"message", "category", "filename", "lineno",
625 "module", "registry", "module_globals", 0};
630 PyObject
*module
= NULL
;
631 PyObject
*registry
= NULL
;
632 PyObject
*module_globals
= NULL
;
634 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "OOOi|OOO:warn_explicit",
635 kwd_list
, &message
, &category
, &filename
, &lineno
, &module
,
636 ®istry
, &module_globals
))
639 if (module_globals
) {
640 static PyObject
*get_source_name
= NULL
;
641 static PyObject
*splitlines_name
= NULL
;
643 PyObject
*module_name
;
645 PyObject
*source_list
;
646 PyObject
*source_line
;
649 if (get_source_name
== NULL
) {
650 get_source_name
= PyString_InternFromString("get_source");
651 if (!get_source_name
)
654 if (splitlines_name
== NULL
) {
655 splitlines_name
= PyString_InternFromString("splitlines");
656 if (!splitlines_name
)
660 /* Check/get the requisite pieces needed for the loader. */
661 loader
= PyDict_GetItemString(module_globals
, "__loader__");
662 module_name
= PyDict_GetItemString(module_globals
, "__name__");
664 if (loader
== NULL
|| module_name
== NULL
)
667 /* Make sure the loader implements the optional get_source() method. */
668 if (!PyObject_HasAttrString(loader
, "get_source"))
670 /* Call get_source() to get the source code. */
671 source
= PyObject_CallMethodObjArgs(loader
, get_source_name
,
675 else if (source
== Py_None
) {
680 /* Split the source into lines. */
681 source_list
= PyObject_CallMethodObjArgs(source
, splitlines_name
,
687 /* Get the source line. */
688 source_line
= PyList_GetItem(source_list
, lineno
-1);
690 Py_DECREF(source_list
);
694 /* Handle the warning. */
695 returned
= warn_explicit(category
, message
, filename
, lineno
, module
,
696 registry
, source_line
);
697 Py_DECREF(source_list
);
702 return warn_explicit(category
, message
, filename
, lineno
, module
,
707 /* Function to issue a warning message; may raise an exception. */
709 PyErr_WarnEx(PyObject
*category
, const char *text
, Py_ssize_t stack_level
)
712 PyObject
*message
= PyString_FromString(text
);
716 if (category
== NULL
)
717 category
= PyExc_RuntimeWarning
;
719 res
= do_warn(message
, category
, stack_level
);
728 /* PyErr_Warn is only for backwards compatability and will be removed.
729 Use PyErr_WarnEx instead. */
734 PyErr_Warn(PyObject
*category
, char *text
)
736 return PyErr_WarnEx(category
, text
, 1);
739 /* Warning with explicit origin */
741 PyErr_WarnExplicit(PyObject
*category
, const char *text
,
742 const char *filename_str
, int lineno
,
743 const char *module_str
, PyObject
*registry
)
746 PyObject
*message
= PyString_FromString(text
);
747 PyObject
*filename
= PyString_FromString(filename_str
);
748 PyObject
*module
= NULL
;
751 if (message
== NULL
|| filename
== NULL
)
753 if (module_str
!= NULL
) {
754 module
= PyString_FromString(module_str
);
759 if (category
== NULL
)
760 category
= PyExc_RuntimeWarning
;
761 res
= warn_explicit(category
, message
, filename
, lineno
, module
, registry
,
771 Py_XDECREF(filename
);
776 PyDoc_STRVAR(warn_doc
,
777 "Issue a warning, or maybe ignore it or raise an exception.");
779 PyDoc_STRVAR(warn_explicit_doc
,
780 "Low-level inferface to warnings functionality.");
782 static PyMethodDef warnings_functions
[] = {
783 {"warn", (PyCFunction
)warnings_warn
, METH_VARARGS
| METH_KEYWORDS
,
785 {"warn_explicit", (PyCFunction
)warnings_warn_explicit
,
786 METH_VARARGS
| METH_KEYWORDS
, warn_explicit_doc
},
787 /* XXX(brett.cannon): add showwarning? */
788 /* XXX(brett.cannon): Reasonable to add formatwarning? */
789 {NULL
, NULL
} /* sentinel */
794 create_filter(PyObject
*category
, const char *action
)
796 static PyObject
*ignore_str
= NULL
;
797 static PyObject
*error_str
= NULL
;
798 static PyObject
*default_str
= NULL
;
799 PyObject
*action_obj
= NULL
;
800 PyObject
*lineno
, *result
;
802 if (!strcmp(action
, "ignore")) {
803 if (ignore_str
== NULL
) {
804 ignore_str
= PyString_InternFromString("ignore");
805 if (ignore_str
== NULL
)
808 action_obj
= ignore_str
;
810 else if (!strcmp(action
, "error")) {
811 if (error_str
== NULL
) {
812 error_str
= PyString_InternFromString("error");
813 if (error_str
== NULL
)
816 action_obj
= error_str
;
818 else if (!strcmp(action
, "default")) {
819 if (default_str
== NULL
) {
820 default_str
= PyString_InternFromString("default");
821 if (default_str
== NULL
)
824 action_obj
= default_str
;
827 Py_FatalError("unknown action");
830 /* This assumes the line number is zero for now. */
831 lineno
= PyInt_FromLong(0);
834 result
= PyTuple_Pack(5, action_obj
, Py_None
, category
, Py_None
, lineno
);
842 PyObject
*filters
= PyList_New(3);
843 const char *bytes_action
;
847 PyList_SET_ITEM(filters
, 0,
848 create_filter(PyExc_PendingDeprecationWarning
, "ignore"));
849 PyList_SET_ITEM(filters
, 1, create_filter(PyExc_ImportWarning
, "ignore"));
850 if (Py_BytesWarningFlag
> 1)
851 bytes_action
= "error";
852 else if (Py_BytesWarningFlag
)
853 bytes_action
= "default";
855 bytes_action
= "ignore";
856 PyList_SET_ITEM(filters
, 2, create_filter(PyExc_BytesWarning
,
859 if (PyList_GET_ITEM(filters
, 0) == NULL
||
860 PyList_GET_ITEM(filters
, 1) == NULL
||
861 PyList_GET_ITEM(filters
, 2) == NULL
) {
871 _PyWarnings_Init(void)
875 m
= Py_InitModule3(MODULE_NAME
, warnings_functions
, warnings__doc__
);
879 _filters
= init_filters();
880 if (_filters
== NULL
)
883 if (PyModule_AddObject(m
, "filters", _filters
) < 0)
886 _once_registry
= PyDict_New();
887 if (_once_registry
== NULL
)
889 Py_INCREF(_once_registry
);
890 if (PyModule_AddObject(m
, "once_registry", _once_registry
) < 0)
893 _default_action
= PyString_FromString("default");
894 if (_default_action
== NULL
)
896 if (PyModule_AddObject(m
, "default_action", _default_action
) < 0)