You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This requires an extra .decode(), which is rather wasteful given that the str is not of any real use.
This came up for me in parsing the output of git cat-file --batch, which must be a binary stream because it contains bytes, but includes header lines like
For reference, bytes.fromhex() was added by @birkenfeld in 0b9b9e0. bytes at that time was a mutable type, later it was renamed to bytearray, and str became new bytes. Initially, fromhex() accepted 8-bit and Unicode strings. It stopped support of 8-bit strings only after making new bytes and new str not interoperable in Python 3.0. So I do not see reasons against supporting bytes here.
I had doubts about supporting the general buffer protocol (see #779 and #71759). The buffer protocol is for binary data, and here we have text data. But it is difficult to decide in which cases to support only bytes, in which bytes and bytearray, and in which any "bytes-like" object.
Note also that the complex constructor only supports str, not bytes (there may be open or closed issue for this).
Activity
Accept bytes in bytes.fromhex()/bytearray.fromhex()
serhiy-storchaka commentedon Feb 20, 2025
You have to look at the discussion that preceded introduction of
bytes.fromhex()or ask the authors of the feature why it only supports str.BTW,
float.fromhex()also only supports str.serhiy-storchaka commentedon Feb 27, 2025
For reference,
bytes.fromhex()was added by @birkenfeld in 0b9b9e0.bytesat that time was a mutable type, later it was renamed tobytearray, andstrbecame newbytes. Initially,fromhex()accepted 8-bit and Unicode strings. It stopped support of 8-bit strings only after making newbytesand newstrnot interoperable in Python 3.0. So I do not see reasons against supportingbyteshere.Accept bytes in bytes.fromhex()/bytearray.fromhex()
Accept bytes in bytes.fromhex()/bytearray.fromhex()
Accept bytes in bytes.fromhex()/bytearray.fromhex()
gh-129349: Accept bytes in bytes.fromhex()/bytearray.fromhex() (#129844)
vstinner commentedon Mar 12, 2025
Implemented in e0637ce.
serhiy-storchaka commentedon Mar 13, 2025
I had doubts about supporting the general buffer protocol (see #779 and #71759). The buffer protocol is for binary data, and here we have text data. But it is difficult to decide in which cases to support only
bytes, in whichbytesandbytearray, and in which any "bytes-like" object.Note also that the
complexconstructor only supportsstr, notbytes(there may be open or closed issue for this).vstinner commentedon Mar 13, 2025
IMO it's convenient to accept bytes when the "text" is ASCII only.