解决不同版本中的 Python bug
我在 Python 中(至少在 2.6.1 中)遇到了 bytearray.fromhex 函数的错误。如果您尝试文档字符串中的示例,就会发生以下情况:
>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str
此示例在 Python 2.7 中运行良好,我想知道解决该问题的最佳编码方法。我不想总是转换为 unicode,因为它会影响性能,并且测试正在使用的 Python 版本感觉不对。
那么有没有更好的方法来解决此类问题,以便它适用于所有版本,最好不会减慢正在运行的 Python 的速度?
I've come across a bug in Python (at least in 2.6.1) for the bytearray.fromhex
function. This is what happens if you try the example from the 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
This example works fine in Python 2.7, and I want to know the best way of coding around the problem. I don't want to always convert to unicode as it's a performance hit, and testing which Python version is being used feels wrong.
So is there a better way to code around this sort of problem so that it will work for all versions, preferably without slowing it down for the working Pythons?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以根据您的需要创建自己的函数来完成这项工作:
然后在代码中使用
my_fromhex
。这样,异常只会发生一次,并且在运行时,可以使用正确的函数,而无需过多的 unicode 转换或异常机制。You can also create your own function to do the work, conditionalized on what you need:
and then use
my_fromhex
in your code. This way, the exception only happens once, and during your runtime, the correct function is used without excess unicode casting or exception machinery.对于这样的情况,最好记住,如果没有抛出异常,
try
块的成本非常低。所以我会使用:这让 Python 2.6 的性能受到很小的影响,但 2.7 根本不应该受到影响。这当然比显式检查 Python 版本更好!
该错误本身(它确实似乎是一个)仍然存在于 Python 2.6.5 中,但我在 bugs.python.org,所以也许它在 2.7 中被意外修复了!它看起来像是向后移植的 Python 3 功能,但在 2.6 中未经过正确测试。
For cases like this it's good to remember that a
try
block is very cheap if no exception is thrown. So I'd use:This lets Python 2.6 work with a small performance hit, but 2.7 shouldn't suffer at all. It's certainly preferable to checking Python version explicitly!
The bug itself (and it certainly does seem to be one) is still present in Python 2.6.5, but I couldn't find any mention of it at bugs.python.org, so maybe it was fixed by accident in 2.7! It looks like a back-ported Python 3 feature that wasn't tested properly in 2.6.