python - UnicodeWarning 只触发一次

标签 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

为什么第二次没有发出警告?我想这与实习有关,但无法弄清楚到底是什么。

我希望得到 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/

相关文章:

debugging - gdb如何在共享库函数中设置软件断点?

python - 如何用 BeautifulSoup [Python] 抓取表格

javascript - 是否可以构造一个匹配 Grapheme Cluster Break=Extend 的\p JavaScript 正则表达式

python - UnicodeDecodeError 帮助 : Data needs to be in ascii for seaborn but source code is in utf-8

Swift 通过 unicode 将国家代码转换为表情符号标志

windows - 操作系统/Windows 内部视频

Python:文件读取器 int 和 if 子句

python - 如何计算 Pandas 系列中重复出现的相同值

python - 在 python 中获取用户输入的 n*n 矩阵

windows - DLLMain lpReserved 参数的真正含义是什么?