我有一个大项目,在各个地方有问题的隐式Unicode转换(coersions)以例如:
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"
显示,它显然已用于某些实际项目中。)
/ edit#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()
构造函数的显式转换,因此它不是我需要的。
/ edit#3:
主题" Extension method for python built-in types!"让我觉得它可能实际上并不容易(至少在CPython中)。
/ edit#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
答案 0 :(得分:4)
您可以注册自定义编码,无论何时使用,都会打印信息:
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字符,有时您不会看到警告。
答案 1 :(得分:2)
您可以做的是:
首先创建自定义编码。我将其称为“lascii”,用于“记录ASCII”:
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”时返回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')
警告:强> 这使用了一些已弃用或未经推荐的功能。它可能效率不高或没有错误。不要在生产中使用,仅用于测试和/或调试。
答案 2 :(得分:2)
只需添加:
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'
>>>
答案 3 :(得分:-3)
我发现您对可能遇到的解决方案进行了大量修改。我只是要解决你原来的帖子,我认为:“我想在unicode构造函数周围创建一个检查输入的包装器。”
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)
我们覆盖现有的函数名称,这样您就不必更改大型项目中的所有调用。您希望在运行时很早就完成此操作,以便后续调用具有新行为。