[Python-Dev] Warnings behave differently in Python 2 and Python 3?

Christoph Groth christoph at grothesque.org
Mon Nov 14 08:58:36 EST 2016


(I assume that this list is appropriate for this topic, but if it 
isn't, I will be grateful for being redirected to the appropriate 
place.)

It seems that warnings behave differently in Python 2 and Python 
3.  Consider the following script.

****************
def func():
    warnings.warn("Blabla", RuntimeWarning)

warnings.simplefilter("ignore")
func()
warnings.simplefilter("always")
func()
****************

When run with CPython 2.7, there is no output, when run with 
CPython 3.5, there is the following output:

****************
/tmp/test.py:4: RuntimeWarning: Blabla
  warnings.warn("Blabla", RuntimeWarning)
****************

Was there indeed a change of how warnings behave in Python 3?  I 
searched, but couldn't find any documentation for this.

Understanding how warnings work is especially important when 
testing for them.
This is how I stumbled across this, in case anyone is interested: 
https://gitlab.kwant-project.org/kwant/kwant/issues/1#note_2608

I also note that the current documentation still uses 
DeprecationWarning in the example of how to suppress a warning: 
https://docs.python.org/dev/library/warnings.html#temporarily-suppressing-warnings. 
Since DeprecationWarning is disabled by default in modern Python, 
perhaps a different warning would provide a better example?


More information about the Python-Dev mailing list