How do I get warnings.warn to issue a warning and not ignore the line? How do I get warnings.warn to issue a warning and not ignore the line? python python

How do I get warnings.warn to issue a warning and not ignore the line?


From the docs:

By default, Python installs several warning filters, which can be overridden by the command-line options passed to -W and calls to filterwarnings().

  • DeprecationWarning and PendingDeprecationWarning, and ImportWarning are ignored.
  • BytesWarning is ignored unless the -b option is given once or twice; in this case this warning is either printed (-b) or turned into an exception (-bb).

By default, DeprecationWarning is ignored. You can change the filters using the following:

warnings.simplefilter('always', DeprecationWarning)

Now your warnings should be printed:

>>> import warnings>>> warnings.simplefilter('always', DeprecationWarning)>>> warnings.warn('test', DeprecationWarning)/home/guest/.env/bin/ipython:1: DeprecationWarning: test  #!/home/guest/.env/bin/python


The warnings module implements filtering of warnings based on certain conditions. You can show the default filters by printing warnings.filters:

$ python -c "import warnings; print(warnings.filters)"[('ignore', None, <type 'exceptions.DeprecationWarning'>, None, 0), ('ignore', None, <type 'exceptions.PendingDeprecationWarning'>, None, 0), ('ignore', None, <type 'exceptions.ImportWarning'>, None, 0), ('ignore', None, <type 'exceptions.BytesWarning'>, None, 0)]

As you can see, DeprecationWarning is ignored by default. You can use the functions in the warnings module and the -W command-line option to Python to configure the filters -- see the documentation for details.

Example:

$ python -WallPython 2.7.3 (default, Sep 26 2013, 20:03:06) [GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import warnings>>> warnings.warn("test", DeprecationWarning)__main__:1: DeprecationWarning: test


$ python -WallPython 2.7.3 (default, Sep 26 2013, 20:03:06) [GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import warnings>>> warnings.warn("test", DeprecationWarning)__main__:1: DeprecationWarning: test