inconsistency in converting from/to hex
ned at nedbatchelder.com
Sun Nov 17 00:35:35 CET 2013
On Saturday, November 16, 2013 5:16:58 PM UTC-5, Laszlo Nagy wrote:
> We can convert from hex str to bytes with bytes.fromhex class method:
> >>> b = bytes.fromhex("ff")
> But we cannot convert from hex binary:
> >>> b = bytes.fromhex(b"ff")
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: must be str, not bytes
> We don't have bytes_instance.tohex() instance method.
> But we have binascii.hexlify. But binascii.hexlify does not return an
> str. It returns a bytes instance instead.
> >>> import binascii
> >>> binascii.hexlify(b)
> Its reverse function binascii.unhexlify can be used on str and bytes too:
> >>> binascii.unhexlify(b'ff')
> >>> binascii.unhexlify('ff')
> * if we have bytes.fromhex() then why don't we have bytes_instance.tohex() ?
> * if the purpose of binascii.unhexlify and bytes.fromhex is the same,
> then why allow binary arguments for the former, and not for the later?
> * in this case, should there be "one obvious way to do it" or not?
The standard library is not always as consistent as we might like. I don't think there is a better answer than that.
This will work if you want to use fromhex with bytes:
b = bytes.fromhex(b"ff".decode("ascii"))
More information about the Python-list