考虑:
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
为什么第二次没有发出警告?我想这与实习有关,但无法弄清楚到底是什么。
我希望得到 cpython 源代码级别的解释。
最佳答案
Python 的默认配置是使用 default
warning configuration (带有 few specific exceptions )。这意味着警告只发出一次每个警告、模块和行。
参见 -W arg
command line switch :
By default, each warning is printed once for each source line where it occurs.
如果在不同的模块或行号中出现相同的比较问题,将再次发出 UnicodeWarning
。
在交互式解释器中,每次你再次输入一些以行号 1 开始的代码块,并且总是在 __main__
模块中执行。因此,您第二次运行比较时,代码再次作为 __main__
模块中的第 1 行运行,,因此警告被抑制了。
如果您在不同的模块或不同的行中触发了问题,您会再次看到警告:
>>> '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
第二次比较再次在第 1 行进行,因此警告被抑制了,但是通过在比较之前添加 if True:
,我们得到了两行并且再次发出了警告。
关于python - UnicodeWarning 只触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28627693/