追踪 Python 中的隐式 unicode 转换 2
Tracking down implicit unicode conversions in Python 2
我有一个大型项目,在多个地方使用了有问题的隐式 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
类型,那就太好了参数设置为默认值,然后通知我(打印回溯等)。
/编辑:
虽然与我正在寻找的内容没有直接关系,但我遇到了这个非常可怕的 hack,用于如何使解码异常完全消失(仅解码异常,即 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 and more recently https://github.com/python/typing/issues/208 上的讨论。
/编辑#5
我也遇到了以下问题,但还没有时间测试它:https://pypi.python.org/pypi/unicode-nazi
我看到你有很多与你可能遇到的解决方案相关的编辑。我只想解决你原来的 post 我认为是:"I want to create a wrapper around the unicode constructor that checks input".
unicode
方法是 Python 标准库的一部分。您将修饰 unicode
方法以向该方法添加检查。
def add_checks(fxn):
def resulting_fxn(*args, **kargs):
# this is where whether the input is of type str
if type(args[0]) is str:
# do something
# this is where the encoding/errors parameters are set to the default values
encoding = 'utf-8'
# Set default error behavior
error = 'ignore'
# Print any information (i.e. traceback)
# print 'blah'
# TODO: for traceback, you'll want to use the pdb module
return fxn(args[0], encoding, error)
return resulting_fxn
使用它看起来像这样:
unicode = add_checks(unicode)
我们覆盖了现有的函数名称,这样您就不必更改大型项目中的所有调用。您希望在运行时尽早执行此操作,以便后续调用具有新行为。
您可以注册自定义编码,在使用时打印一条消息:
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 字符,有时您不会看到警告。
您可以做的是:
首先创建自定义编码。对于 "logging ASCII":
,我将其命名为 "lascii"
import codecs
import traceback
def lascii_encode(input,errors='strict'):
print("ENCODED:")
traceback.print_stack()
return codecs.ascii_encode(input)
def lascii_decode(input,errors='strict'):
print("DECODED:")
traceback.print_stack()
return codecs.ascii_decode(input)
class Codec(codecs.Codec):
def encode(self, input,errors='strict'):
return lascii_encode(input,errors)
def decode(self, input,errors='strict'):
return lascii_decode(input,errors)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
print("Incremental ENCODED:")
traceback.print_stack()
return codecs.ascii_encode(input)
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
print("Incremental DECODED:")
traceback.print_stack()
return codecs.ascii_decode(input)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
def getregentry():
return codecs.CodecInfo(
name='lascii',
encode=lascii_encode,
decode=lascii_decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamwriter=StreamWriter,
streamreader=StreamReader,
)
它的作用与 ASCII 编解码器基本相同,只是它在每次从 unicode 编码或解码为 lascii 时打印一条消息和当前堆栈跟踪。
现在您需要使其对编解码器模块可用,以便可以通过名称 "lascii" 找到它。为此,您需要创建一个搜索函数,当它被输入字符串 "lascii" 时 returns lascii-codec。然后将其注册到编解码器模块:
def searchFunc(name):
if name=="lascii":
return getregentry()
else:
return None
codecs.register(searchFunc)
现在剩下要做的最后一件事是告诉 sys 模块使用 'lascii' 作为默认编码:
import sys
reload(sys) # necessary, because sys.setdefaultencoding is deleted on start of Python
sys.setdefaultencoding('lascii')
警告:
这使用了一些已弃用或不推荐的功能。它可能效率不高或没有错误。请勿在生产中使用,仅用于测试and/or调试。
只需添加:
from __future__ import unicode_literals
在源代码文件的开头 - 它必须是第一个导入,并且必须在所有受影响的源代码文件中,并且在 Python-2.7 中使用 unicode 的头痛消失了。如果你没有对字符串做任何非常奇怪的事情,那么它应该立即解决这个问题。
从我的控制台查看以下复制和粘贴 - 我尝试使用您问题中的示例:
user@linux2:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> someDynamicStr = "bar" # could come from various sources
>>>
>>> # works
... u"foo" + someDynamicStr
u'foobar'
>>> u"foo{}".format(someDynamicStr)
u'foobar'
>>>
>>> someDynamicStr = "\xff" # uh-oh
>>>
>>> # raises UnicodeDecodeError
... u"foo" + someDynamicStr
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
uUnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
">>> u"foo{}".format(someDynamicStr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
>>>
现在有了 __future__
魔法:
user@linux2:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> someDynamicStr = "bar" # could come from various sources
>>>
>>> # works
... u"foo" + someDynamicStr
u'foobar'
>>> u"foo{}".format(someDynamicStr)
u'foobar'
>>>
>>> someDynamicStr = "\xff" # uh-oh
>>>
>>> # raises UnicodeDecodeError
... u"foo" + someDynamicStr
u'foo\xff'
>>> u"foo{}".format(someDynamicStr)
u'foo\xff'
>>>
我有一个大型项目,在多个地方使用了有问题的隐式 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
类型,那就太好了参数设置为默认值,然后通知我(打印回溯等)。
/编辑:
虽然与我正在寻找的内容没有直接关系,但我遇到了这个非常可怕的 hack,用于如何使解码异常完全消失(仅解码异常,即 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 and more recently https://github.com/python/typing/issues/208 上的讨论。
/编辑#5
我也遇到了以下问题,但还没有时间测试它:https://pypi.python.org/pypi/unicode-nazi
我看到你有很多与你可能遇到的解决方案相关的编辑。我只想解决你原来的 post 我认为是:"I want to create a wrapper around the unicode constructor that checks input".
unicode
方法是 Python 标准库的一部分。您将修饰 unicode
方法以向该方法添加检查。
def add_checks(fxn):
def resulting_fxn(*args, **kargs):
# this is where whether the input is of type str
if type(args[0]) is str:
# do something
# this is where the encoding/errors parameters are set to the default values
encoding = 'utf-8'
# Set default error behavior
error = 'ignore'
# Print any information (i.e. traceback)
# print 'blah'
# TODO: for traceback, you'll want to use the pdb module
return fxn(args[0], encoding, error)
return resulting_fxn
使用它看起来像这样:
unicode = add_checks(unicode)
我们覆盖了现有的函数名称,这样您就不必更改大型项目中的所有调用。您希望在运行时尽早执行此操作,以便后续调用具有新行为。
您可以注册自定义编码,在使用时打印一条消息:
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 字符,有时您不会看到警告。
您可以做的是:
首先创建自定义编码。对于 "logging ASCII":
,我将其命名为 "lascii"import codecs
import traceback
def lascii_encode(input,errors='strict'):
print("ENCODED:")
traceback.print_stack()
return codecs.ascii_encode(input)
def lascii_decode(input,errors='strict'):
print("DECODED:")
traceback.print_stack()
return codecs.ascii_decode(input)
class Codec(codecs.Codec):
def encode(self, input,errors='strict'):
return lascii_encode(input,errors)
def decode(self, input,errors='strict'):
return lascii_decode(input,errors)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
print("Incremental ENCODED:")
traceback.print_stack()
return codecs.ascii_encode(input)
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
print("Incremental DECODED:")
traceback.print_stack()
return codecs.ascii_decode(input)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
def getregentry():
return codecs.CodecInfo(
name='lascii',
encode=lascii_encode,
decode=lascii_decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamwriter=StreamWriter,
streamreader=StreamReader,
)
它的作用与 ASCII 编解码器基本相同,只是它在每次从 unicode 编码或解码为 lascii 时打印一条消息和当前堆栈跟踪。
现在您需要使其对编解码器模块可用,以便可以通过名称 "lascii" 找到它。为此,您需要创建一个搜索函数,当它被输入字符串 "lascii" 时 returns lascii-codec。然后将其注册到编解码器模块:
def searchFunc(name):
if name=="lascii":
return getregentry()
else:
return None
codecs.register(searchFunc)
现在剩下要做的最后一件事是告诉 sys 模块使用 'lascii' 作为默认编码:
import sys
reload(sys) # necessary, because sys.setdefaultencoding is deleted on start of Python
sys.setdefaultencoding('lascii')
警告: 这使用了一些已弃用或不推荐的功能。它可能效率不高或没有错误。请勿在生产中使用,仅用于测试and/or调试。
只需添加:
from __future__ import unicode_literals
在源代码文件的开头 - 它必须是第一个导入,并且必须在所有受影响的源代码文件中,并且在 Python-2.7 中使用 unicode 的头痛消失了。如果你没有对字符串做任何非常奇怪的事情,那么它应该立即解决这个问题。
从我的控制台查看以下复制和粘贴 - 我尝试使用您问题中的示例:
user@linux2:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> someDynamicStr = "bar" # could come from various sources
>>>
>>> # works
... u"foo" + someDynamicStr
u'foobar'
>>> u"foo{}".format(someDynamicStr)
u'foobar'
>>>
>>> someDynamicStr = "\xff" # uh-oh
>>>
>>> # raises UnicodeDecodeError
... u"foo" + someDynamicStr
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
uUnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
">>> u"foo{}".format(someDynamicStr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
>>>
现在有了 __future__
魔法:
user@linux2:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> someDynamicStr = "bar" # could come from various sources
>>>
>>> # works
... u"foo" + someDynamicStr
u'foobar'
>>> u"foo{}".format(someDynamicStr)
u'foobar'
>>>
>>> someDynamicStr = "\xff" # uh-oh
>>>
>>> # raises UnicodeDecodeError
... u"foo" + someDynamicStr
u'foo\xff'
>>> u"foo{}".format(someDynamicStr)
u'foo\xff'
>>>