geo*_*org 7 python unicode internals
考虑:
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
Run Code Online (Sandbox Code Playgroud)
为什么不是第二次发出警告?我想这与实习有关,但无法弄清楚到底是什么.
我很欣赏cpython-source级别的解释.
Python的默认配置是使用default警告配置(有一些特定的例外).这意味着每个警告,模块和线路只发出一次警告.
请参阅-W arg命令行开关:
默认情况下,每个警告都会针对发生它的每个源行打印一次.
所述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
Run Code Online (Sandbox Code Playgroud)
第二次比较再次在第1行,因此警告被抑制,但通过if True:在比较之前添加我们得到两行并且再次发出警告.