How to inspect the warnings filter?

Viewed 86

In python, it is possible to change the way warnings are handled by working with the Warnings Filter. For example, one can add a filter specification to the warnings filter by calling warnings.simplefilter, by working with the PYTHONWARNINGS environment variable, or by using the -W command-line flag.

How can I inspect the current state of the warnings filter to see what warnings will be filtered, turned into error messages, etc?

1 Answers

The warnings module maintains a global variable filters.

>>> import warnings
>>> warnings.filters
[('default', None, <class 'DeprecationWarning'>, '__main__', 0),
('ignore', None, <class 'DeprecationWarning'>, None, 0),
('ignore', None, <class 'PendingDeprecationWarning'>, None, 0),
('ignore', None, <class 'ImportWarning'>, None, 0),
('ignore', None, <class 'ResourceWarning'>, None, 0)]

FWIW, I found this by looking at the code for warnings.filterwarnings, which, via _add_filter(), references a filters global variable imported from the C module _warnings.

Related