解决不同版本的Python bug

Dan*_*use 5 python python-2.6 python-2.7

我在这个bytearray.fromhex函数中遇到了Python中的错误(至少在2.6.1中).如果您尝试使用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
Run Code Online (Sandbox Code Playgroud)

这个例子在Python 2.7中运行良好,我想知道编码问题的最佳方法.我不想总是转换为unicode,因为它是性能损失,并且测试使用哪个Python版本感觉不对.

那么是否有更好的方法来编码这类问题,以便它适用于所有版本,最好不要为工作的Pythons减慢速度?

Sco*_*ths 8

对于这样的情况,try如果没有抛出异常,记住块非常便宜是件好事.所以我用:

try:
    x = bytearray.fromhex(some_str)
except TypeError:
    # Work-around for Python 2.6 bug 
    x = bytearray.fromhex(unicode(some_str))
Run Code Online (Sandbox Code Playgroud)

这使得Python 2.6的性能受到很小影响,但2.7应该不会受到影响.明确检查Python版本当然更可取!

错误本身(它似乎确实是一个)仍然存在于Python 2.6.5中,但我在bugs.python.org上找不到任何提及它,所以也许它在2.7中偶然修复了!它看起来像是一个后端移植的Python 3功能,在2.6中没有正确测试.