Summary of Common Functions of UUID Module in Python

UUID is usually used to generate unique identifiers, such as the ID field of the database, user account number, etc.

The following are some commonly used functions, for more information: https://docs.python.org/3/library/uuid.html.

uuid.uuid1(node=None, clock_seq=None)

Generate a UUID from a host ID, sequence number, and the current time. If node is not given, getnode() is used to obtain the hardware address. If clock_seq is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.

uuid.uuid3(namespace, name)

Generate a UUID based on the MD5 hash of a namespace identifier (which is a UUID) and a name (which is a bytes object or a string that will be encoded using UTF-8).

uuid.uuid4()

Generate a random UUID.

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 bytes object or a string that will be encoded using UTF-8).

Note: You can also output uuid in different forms through hex, int, bytes and other attributes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import uuid

id_1 = uuid.uuid1()
print("uuid_1:" + str(id_1))
print("uuid_1.hex:" + str(id_1.hex))
print("uuid_1.int:" + str(id_1.int))
print("uuid_1.urn:" + str(id_1.urn))
print("uuid_1.bytes:" + str(id_1.bytes))
print("uuid_1.bytes_le:" + str(id_1.bytes_le) + "\n")

id_3 = uuid.uuid3(uuid.NAMESPACE_DNS, "example")
print("uuid_3:" + str(id_3) + "\n")

id_4 = uuid.uuid4()
print("uuid_4:" + str(id_4) + "\n")

id_5 = uuid.uuid5(uuid.NAMESPACE_DNS, "example")
print("uuid_5:" + str(id_5) + "\n")

The output is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
uuid_1:ea834337-38b2-11f0-aafd-d444ca5de201
uuid_1.hex:ea83433738b211f0aafdd444ca5de201
uuid_1.int:311720905198677193690942071098901914113
uuid_1.urn:urn:uuid:ea834337-38b2-11f0-aafd-d444ca5de201
uuid_1.bytes:b'\xea\x83C78\xb2\x11\xf0\xaa\xfd\xd4D\xca]\xe2\x01'
uuid_1.bytes_le:b'7C\x83\xea\xb28\xf0\x11\xaa\xfd\xd4D\xca]\xe2\x01'

uuid_3:c5e5f349-28ef-3f5a-98d6-0b32ee4d1743

uuid_4:6a10d447-9df6-4803-949d-1a4e23fccf40

uuid_5:7cb48787-6d91-5b9f-bc60-f30298ea5736