在不同版本中解决Python bug
我在Python中(至少在2.6.1中)遇到了一个关于在不同版本中解决Python bug,python,python-2.7,python-2.6,Python,Python 2.7,Python 2.6,我在Python中(至少在2.6.1中)遇到了一个关于bytearray.fromhex函数的bug。如果您尝试docstring中的示例,就会出现这种情况: >>> bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: fromhex() argument 1 must be uni
bytearray.fromhex
函数的bug。如果您尝试docstring中的示例,就会出现这种情况:
>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str
>>bytearray.fromhex('B9 01EF')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:fromhex()参数1必须是unicode,而不是str
这个例子在Python2.7中运行良好,我想知道解决这个问题的最佳编码方法。我不想总是转换为unicode,因为这会影响性能,而且测试使用的Python版本感觉是错误的
那么,有没有更好的方法来编码这类问题,以便它能适用于所有版本,最好是不会减慢Python的工作速度?对于这样的情况,最好记住,如果没有引发异常,一个
try
块是非常便宜的。所以我会用:
try:
x = bytearray.fromhex(some_str)
except TypeError:
# Work-around for Python 2.6 bug
x = bytearray.fromhex(unicode(some_str))
这使得Python2.6在性能上受到了很小的影响,但2.7应该不会受到任何影响。这当然比显式检查Python版本更可取
Python2.6.5中仍然存在这个bug(它看起来确实是一个bug),但我在上一篇文章中找不到任何关于它的内容,所以可能是在2.7中意外修复的!它看起来像是一个后端口的Python 3功能,在2.6中没有经过正确测试。您也可以创建自己的函数来完成这项工作,并根据需要设置条件:
def my_fromhex(s):
return bytearray.fromhex(s)
try:
my_fromhex('hello')
except TypeError:
def my_fromhex(s):
return bytearray.fromhex(unicode(s))
然后在代码中使用my_fromhex
。这样,异常只发生一次,并且在运行时使用正确的函数,而不需要过多的unicode强制转换或异常机制