Consider:
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 'abc' == u'abc'
True
>>> 'ab\xDF' == u'abc'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
>>> 'ab\xDF' == u'abc'
False
Why isn't the warning fired for the second time? I guess this has something to do with interning, but can't figure out what exactly.
I'd appreciate a cpython-source level explanation.
The default configuration for Python is to use the default
warning configuration (with a few specific exceptions). This means that warnings are emitted just once per warning, module and line.
See the -W arg
command line switch:
By default, each warning is printed once for each source line where it occurs.
The UnicodeWarning
will be emitted again if the same comparison problem arises in a different module or line number.
In the interactive interpreter, every time you enter some code that block starts with line number 1 again, and are always executed in the __main__
module. So the second time you ran the comparison, the code ran as line 1 in the __main__
module again, so the warning was suppressed.
If you triggered the issue in a different module, or on different lines, you'd see the warning again:
>>> 'ab\xDF' == u'abc'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
>>> 'ab\xDF' == u'abc'
False
>>> if True:
... 'ab\xDF' == u'abc'
...
__main__:2: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
The second comparison was on line 1 again, so the warning was suppressed, but by adding if True:
before the comparison we got two lines and the warning was emitted again.
Seems that there is 'once' value for attribute 'action' for UnicodeWarning:
https://docs.python.org/2/library/warnings.html#the-warnings-filter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With