WoJ
WoJ

Reputation: 29987

How to generate a UUID compliant with RFC4122?

I am trying to create a UUID that follows the RFC4122 requirements. The documentation for UUID v5 states:

uuid.uuid5(namespace, name)
Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a UUID) and a name (which is a string).

and

uuid.RFC_4122
Specifies the UUID layout given in RFC 4122.

I do not understand what the "name" in the explanation above is:

>>> import uuid
>>> uuid.uuid5(uuid.RFC_4122, 'hello') 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python310\lib\uuid.py", line 720, in uuid5
    hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
AttributeError: 'str' object has no attribute 'bytes'

It is surprisingly difficult to find an example of the generation of this UUID (I could not find any, anywhere).

Upvotes: 1

Views: 4201

Answers (1)

pigrammer
pigrammer

Reputation: 3489

The uuid module is almost always following RFC 4122. That is, if you use one of the uuidx functions, it should give an RFC 4122 UUID. uuid.RFC_4122 is not a namespace; it's just a string that says 'specified in RFC 4122'. The namespaces are:

To generate an RFC 4122 UUID, use one of these functions:

  • uuid1
    Generate a UUID from the time and hostname.
  • uuid3
    Generate a UUID from an MD5 hash of one of the namespaces above and a name.
  • Preferred: uuid4
    Generate a random UUID.
  • uuid5
    Generate a UUID from an SHA1 hash of one of the namespaces above and a name.

It's preferred to use uuid.uuid4(), because it's actually random.

You can actually check that a UUID uses RFC 4122:

In [1]: import uuid

In [2]: my_UUID = uuid.uuid4()

In [3]: my_UUID.variant
Out[3]: 'specified in RFC 4122'

In [4]: my_UUID
Out[4]: UUID('2721ffc3-f8a9-417e-a124-af057434a3af')

Note: for obvious reasons, you won't get the same UUID as me.

Upvotes: 3

Related Questions