UnicodeWarning only starts 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 does the second warning not work? I suppose this has something to do with internment, but cannot figure out what exactly.

I would appreciate the cpython source level explanation.

+7
python internals unicode
source share
2 answers

The default configuration for Python is to use the default configuration (with a few special exceptions ). This means that warnings are issued only 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 this occurs.

UnicodeWarning will exit again if the same comparison problem occurs in another module or line number.

In the interactive interpreter, every time you enter some code that starts with line number 1 and is always executed in the __main__ module. So, the second time you performed the comparison, the code is run again as line 1 in the __main__ module, so the warning was suppressed.

If you caused a problem in another module or in different lines, you will again see a warning:

 >>> '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 again on line 1, so the warning was suppressed, but by adding if True: before the comparison, we got two lines, and the warning was issued again.

+5
source share

It seems that the value is "once" for the "attribute" for UnicodeWarning:

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

+4
source share

All Articles