Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnicodeWarning fired only once

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.

like image 987
georg Avatar asked Feb 20 '15 11:02

georg


2 Answers

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.

like image 70
Martijn Pieters Avatar answered Nov 06 '22 23:11

Martijn Pieters


Seems that there is 'once' value for attribute 'action' for UnicodeWarning:

https://docs.python.org/2/library/warnings.html#the-warnings-filter

like image 31
Eugene Soldatov Avatar answered Nov 06 '22 22:11

Eugene Soldatov