我可以关闭隐式 Python unicode 转换来查找混合字符串错误吗?

2024-02-07

在分析我们的代码时,我惊讶地发现数百万次调用
C:\Python26\lib\encodings\utf_8.py:15(解码)

我开始调试,发现我们的代码库中存在许多小错误,通常是将字符串与 unicode 进行比较,或者添加字符串和 unicode。 Python 会优雅地解码字符串并以 unicode 执行以下操作。

多么体贴。但很贵!

我对 unicode 很流利,读过乔尔·斯波尔斯基 http://www.joelonsoftware.com/articles/Unicode.html and 深入Python http://xshi.org/web-1.0/notes/diveintopython-5.4/html/xml_processing/unicode.html...

我尝试将我们的代码内部仅保留为 unicode。

我的问题 - 我可以关闭这种Python式的好人行为吗?至少在我找到所有这些错误并修复它们之前(通常通过添加 u'u')?

其中一些非常难以找到(有时是字符串的变量......)。

Python 2.6.5(我无法切换到3.x)。


以下应该有效:

>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('undefined')
>>> u"abc" + u"xyz"
u'abcxyz'
>>> u"abc" + "xyz"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/encodings/undefined.py", line 22, in decode
    raise UnicodeError("undefined encoding")
UnicodeError: undefined encoding

reload(sys)上面的代码片段中只需要在这里,因为通常sys.setdefaultencoding应该去sitecustomize.pyPython 中的文件site-packages目录(建议这样做)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以关闭隐式 Python unicode 转换来查找混合字符串错误吗? 的相关文章

随机推荐