Skip to content

bpo-29729: uuid.UUID now accepts bytes-like object #3801

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Lib/test/test_uuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,11 @@ def testIssue8621(self):

self.assertNotEqual(parent_value, child_value)

def test_bytes_like(self):
u = uuid.uuid4()
self.assertEqual(uuid.UUID(bytes=memoryview(u.bytes)), u)
self.assertEqual(uuid.UUID(bytes=bytearray(u.bytes)), u)


class TestInternals(unittest.TestCase):
@unittest.skipUnless(os.name == 'posix', 'requires Posix')
Expand Down
1 change: 0 additions & 1 deletion Lib/uuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
if bytes is not None:
if len(bytes) != 16:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

>>> a = array.array('i', [-1]*4)
>>> x = int.from_bytes(a, byteorder='big')
>>> len(a)
4
>>> x.bit_length()/8
16.0

And conversely:

>>> a = array.array('i', [-1]*16)
>>> x = int.from_bytes(a, byteorder='big')
>>> len(a)
16
>>> x.bit_length()/8
64.0

raise ValueError('bytes is not a 16-char string')
assert isinstance(bytes, bytes_), repr(bytes)
int = int_.from_bytes(bytes, byteorder='big')
if fields is not None:
if len(fields) != 6:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
uuid.UUID now accepts bytes-like object. The constructor doesn't require the
'bytes' argument to be an instance of bytes: accept bytes-like types,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... and 'bytes_le'

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, fixed.

bytearray and memoryview for example.