我有一个大型项目,在不同的地方使用了有问题的隐式 Unicode 转换(强制转换),例如:
someDynamicStr = "bar" # could come from various sources
# works
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)
someDynamicStr = "\xff" # uh-oh
# raises UnicodeDecodeError
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)
(也可能是其他形式。)
现在我想追踪这些用法,尤其是那些在活跃使用的代码中的用法。
如果我可以轻松地将 unicode
构造函数替换为包装器,它会检查输入是否属于 str
类型和 encoding
/errors
参数设置为默认值,然后通知我(打印回溯等)。
/编辑:
虽然与我正在寻找的内容没有直接关系,但我遇到了如何使解码异常完全消失的这个非常可怕的黑客攻击(仅解码异常,即 str
到 unicode
,但反之则不然,参见 https://mail.python.org/pipermail/python-list/2012-July/627506.html )。
我不打算使用它,但对于那些解决无效 Unicode 输入问题并寻求快速修复的人来说,它可能会很有趣(但请考虑副作用):
import codecs
codecs.register_error("strict", codecs.ignore_errors)
codecs.register_error("strict", lambda x: (u"", x.end)) # alternatively
(在互联网上搜索 codecs.register_error("strict"
显示它显然在一些实际项目中使用。)
/编辑#2:
对于显式转换,我在 a SO post on monkeypatching 的帮助下做了一个片段:
class PatchedUnicode(unicode):
def __init__(self, obj=None, encoding=None, *args, **kwargs):
if encoding in (None, "ascii", "646", "us-ascii"):
print("Problematic unicode() usage detected!")
super(PatchedUnicode, self).__init__(obj, encoding, *args, **kwargs)
import __builtin__
__builtin__.unicode = PatchedUnicode
这只会影响直接使用 unicode()
构造函数的显式转换,所以这不是我需要的。
/编辑#3:
线程“Extension method for python built-in types!”让我觉得这实际上可能不容易实现(至少在 CPython 中)。
/编辑#4:
很高兴在这里看到很多好的答案,可惜我只能给出一次赏金。
与此同时,我遇到了一个有点类似的问题,至少在这个人试图实现的意义上是这样:Can I turn off implicit Python unicode conversions to find my mixed-strings bugs? 请注意,在我的情况下,抛出异常不会是可以的。在这里,我正在寻找可能指向有问题代码的不同位置的东西(例如,通过打印 smth.)但不是可能退出程序或改变其行为的东西(因为这样我可以优先修复什么)。
另一方面,从事 Mypy 项目的人员(包括 Guido van Rossum)将来也可能会想出类似的有用的东西,请参阅 https://github.com/python/mypy/issues/1141 上的讨论。最近https://github.com/python/typing/issues/208 .
/edit #5
我也遇到了以下但还没有时间测试它:https://pypi.python.org/pypi/unicode-nazi
最佳答案
您可以注册一个自定义编码,在使用时打印一条消息:
ourencoding.py
中的代码:
import sys
import codecs
import traceback
# Define a function to print out a stack frame and a message:
def printWarning(s):
sys.stderr.write(s)
sys.stderr.write("\n")
l = traceback.extract_stack()
# cut off the frames pointing to printWarning and our_encode
l = traceback.format_list(l[:-2])
sys.stderr.write("".join(l))
# Define our encoding:
originalencoding = sys.getdefaultencoding()
def our_encode(s, errors='strict'):
printWarning("Default encoding used");
return (codecs.encode(s, originalencoding, errors), len(s))
def our_decode(s, errors='strict'):
printWarning("Default encoding used");
return (codecs.decode(s, originalencoding, errors), len(s))
def our_search(name):
if name == 'our_encoding':
return codecs.CodecInfo(
name='our_encoding',
encode=our_encode,
decode=our_decode);
return None
# register our search and set the default encoding:
codecs.register(our_search)
reload(sys)
sys.setdefaultencoding('our_encoding')
如果您在我们脚本的开头导入此文件,那么您将看到隐式转换的警告:
#!python2
# coding: utf-8
import ourencoding
print("test 1")
a = "hello " + u"world"
print("test 2")
a = "hello ☺ " + u"world"
print("test 3")
b = u" ".join(["hello", u"☺"])
print("test 4")
c = unicode("hello ☺")
输出:
test 1
test 2
Default encoding used
File "test.py", line 10, in <module>
a = "hello ☺ " + u"world"
test 3
Default encoding used
File "test.py", line 13, in <module>
b = u" ".join(["hello", u"☺"])
test 4
Default encoding used
File "test.py", line 16, in <module>
c = unicode("hello ☺")
它并不完美,如测试 1 所示,如果转换后的字符串仅包含 ASCII 字符,有时您不会看到警告。
关于python - 追踪 Python 2 中的隐式 unicode 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39662847/