Skip to content
Advertisement

Decode UUID 4 as a Python string

I would like to generate a UUID v4 string starting from the uuid import from the Python standard library.

I know I can cast a UUID to str by doing str(uuid.uuid4()), however I am trying to understand what the bytes in that class instance mean. While trying to decode those bytes I see all sorts of errors, either the string is not the one I expect, or an exception is thrown. I think these bytes are UTF-16 encoded as per documentation here https://docs.python.org/3/library/uuid.html#uuid.UUID.bytes

UUID instances have these read-only attributes:

UUID.bytes The UUID as a 16-byte string (containing the six integer fields in big-endian byte order).

However what I get from those fields is not the expected UUID I get when casting to str, why is this happening?

JavaScript

Advertisement

Answer

Decoding bytes is for text not structures so do not try to decode them. To inspect the bytes, use .hex():

JavaScript

Output:

JavaScript

See this Raymond Chen “Old New Thing” blog article about GUIDS for more information and why the 6 integer fields are printed as 5.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement