Python UUID Easy Examples to generate UUID

 

Introduction to Python UUID

Universally Unique Identifiers, also known as UUIDs, are 128-bit numbers used to uniquely identify information in computer systems. UUIDs can be used to refer to a wide variety of elements including documents, objects, sessions, tokens, entities, and so on. They can also be used as database keys. In this article, we will discuss the Python UUID module.

We will learn how we can use this module to generate unique IDs through various examples and will discuss why we use it. Moreover, we will also cover some of the methods that are available in this module and will use them to generate different UUIDs. In a nutshell, this tutorial will contain all the necessary information and python examples that are required in order to start working with the Python UUID module.

Advertisement

 

Getting Started with Python UUID

As we already discussed that UUID stands for Universally Unique Identifier. Sometimes is also call it a GUID( globally Unique Identifier). Python UUID module is used to generate a random object of 128 bits. This library generates unique IDs based on the system time and the network address of the computer. The UUID object is immutable and it contains some functions to create various unique IDs. In this section, we will discuss the structure of UUID and why we use it in Python.

 

The basic structure of UUID

The UUID is made up of five components, and each component has a fixed length. A hyphen symbol separates each component. We can present a UUID in the format “8-4-4-4-12” where each of the digits represents the length in hex digits. The following diagram shows the basic structure of a UUID. See the diagram below:

Python uuid

In the diagram above, you can see the five different components of UUID. Now see the table below which shows again shows these components and the size of each of them.

Name Length (hex digits)Length (bits)Contents
time_low832integer giving the low 32 bits of the time
time_mid416integer giving the middle 16 bits of the time
time_hi_and_version4164-bit "version" in the most significant bits, followed by the high 12 bits of the time
clock_seq_hi_and_res clock_seq_low4161 to 3-bit "variant" in the most significant bits, followed by the 13 to 15-bit clock sequence
node1248the 48-bit node id

 

When to use Python UUID?

Mostly the usage of the Python UUID depends on the situation, use case, conditions, and complexity. The following list highlights some of the applications and usages of UUIDs. See the list below:

  • To Generate unique Uniform Resource Names.
  • We can even use UUID as a transaction ID
  • Notable uses in cryptographic applications
  • UUID’s are also handy for generating the unique session id to help state management.
  • UUID has a significant advantage in the database because it is environment-independent which means the UUID generated on any machine using any application is universally unique.
  • As most of the applications are dependent on the underlying database server to generate a unique or primary key. What if we want to change the database in which the key generation is different. In such a case, a good option is to use UUID in your application to generate a unique database key.

 

Method-1: Python UUID 1 to generate unique IDs

The Python uuid.uuid1() function is used to generate a UUID from the host ID, sequence number, and the current time. It uses the MAC address of a host as a source of uniqueness. A MAC address is simply the physical address, which uniquely identifies each device on a given network. It stands for Media Access Control and is also known as Physical address, hardware address, or BIA (Burned In Address). It is globally unique which means two devices cannot have the same MAC address. In this section, we will see the syntax of the Python uuid1() function and will solve an example.

 

Syntax of Python UUID 1

The syntax of UUID 1 is very simple. It has two parameters; one for node and another for clock_seq. See the syntax below:

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

Both of the parameters are optional. The node is the hardware address which is a 48-bit positive integer. If the node is not provided then the uuid.getnode() method is used to obtain the Universally administered MAC address of the current host. If the clock_seq is not provided, then a random 14-bit sequence number is chosen.

 

Example to generate unique ID using Python UUID1() method

Now let us take an example and see how we can use uuid1() method to generate a unique ID. Before going into the UUID1() method, it is required to import the python UUID module using the import keyword. See the example below:

# Importing the uuid module
import uuid
# Generate a UUID from a host ID, sequence number, and the current time
My_uuid = uuid.uuid1()
# printing my_uuid
print(My_uuid)

Output:

cefe23ae-37b8-11ec-adb3-9b73810828e1

The Python uuid1 is not safe it has privacy concerns because it shows the computer’s network address in UUID. Now let us provide the optional arguments and generate a unique ID again. See the example below:

# Importing the  uuid module
import uuid
# Generate a UUID using a clock sequence and node
clock_seq = 5225
node = 0xccaf789d94a0
# generating uuid 1
my_uuid = uuid.uuid1(node, clock_seq)
# printing
print(my_uuid)

Output:

52f2562e-37b9-11ec-9469-ccaf789d94a0

Notice that in the example above, we had provided the optional arguments as well.

 

Method-2: Python UUID 4 to generate random UUID

The Python UUID generated using a uuid4() function is created using a truly Random or Pseudo-Random generator. That is why the chance of a collision is small. When UUIDs require to generate on separate machines, or we want to generate secure UUIDs use UUID4(). It is also used to generate cryptographically secure random numbers. In this section, we will learn about the syntax of UUID 4 and will solve an example as well.

 

Syntax of Python UUID 4

The Python UUID 4 does not take any arguments and its syntax is very simple. See the syntax below:

Advertisement
uuid.uuid4()

This function will return random UUID values each time.

 

Example of Python UUID 4 to generate random UUID

Now let us take an example and see how we can generate a random UUID using Python uuid.uuid4() method. See the example below:

# importing  uuid module
import uuid
# Initialize the variable
num = 0
# Iterating using while loop to produce 5 UUIDs 
while(num<5):
  # Generate a random number using UUID 4 method
  print(num, "----->",uuid.uuid4())
  # Increment the value by one
  num+=1

Output:

0 -----> 8ba2fe3f-83d3-45d0-a555-8bc52cbcc93a
1 -----> fabfe09a-bb27-4c8a-96d5-47b751088912
2 -----> a471df13-f444-4a37-bbfa-a822303177b0
3 -----> 77114a31-4282-4e1e-a150-27664954a8f4
4 -----> b2aa8e1f-6bea-46b5-a388-09892bc26edf

Notice that in each of the iteration we had got different UUID because the uuid4() method generates random UUIDs.

 

Method-3: Python UUID 3  to create a name-based UUID

The UUID3 is used for generating UUIDs from “names.” we can use name and namespace to create a series of unique UUIDs. In simple words, version, 3 UUID is nothing but hashing namespace identifier with a name.  The uuid3() generates a UUID based on the MD5 hash of a namespace identifier and a string. An MD5 hash is created by taking a string of any length and encoding it into a 128-bit fingerprint.  MD5 hashes are commonly used with smaller strings when storing passwords, credit card numbers, or other sensitive data in databases such as the popular MySQL. In this section, we will see the syntax of UUID3 and will solve an example as well.

 

Syntax of Python UUID 3

The syntax of Python UUID3 is simple. It takes two arguments; namespace and name. See the syntax below:

uuid.uuid3(namespace, name)

This will return a UUID based on MD5 hash technique of a namespace identifier and a string.

 

Example of Python UUID 3 to create a name-based UUID

Now let us take an example and see how we can use the python uuid3() method to generate name-based UUID. See the example below:

Advertisement
# importing uuid module
import uuid
# creating names of list
hostNames = ['golinuxcloud.com', 'stackoverflow.com']
# using for loop to iterate through the names
for host in hostNames:
    # python uuid to create name-based UUID
    print(uuid.uuid3(uuid.NAMESPACE_DNS, host)) 

Output:

63df0dc6-9b75-3523-b673-e5b20a96bb63
6d079ab3-a985-3dc7-8086-3dc32dc08cb9

Notice that we get the UUID based on the name that we provided.

 

Method-4: Python UUID 5 to create name-based UUID

Similar to python uuid3(), the python uuid5() is also used to create named-based UUID. But it generates a UUID based on the SHA-1 hashing technique of a namespace identifier and a name rather than the MD5 hashing technique. In this section, we will discuss the syntax of UUID 5 and will solve a problem as well.

 

Syntax of Python UUID 5

The syntax of Python UUID5 is simple. It takes two arguments; namespace and name. See the syntax below:

uuid.uuid5(namespace, name)

This will return a UUID based on SHA-1 technique of creating a UUID.

 

Example of Python UUID 5 to create a name-based UUID

Now let us take an example and see how we can use the python uuid5() method to generate name-based UUID. See the example below:

# importing uuid module
import uuid
# creating hostNames
hostNames = ['golinuxcloud.com', 'stackoverflow.com']
# using for loop to iterate
for host in hostNames:
    # printing the UUID based on name and host
    print(uuid.uuid5(uuid.NAMESPACE_DNS, host))

Output:

32f655ca-b2f8-523b-836f-4c008c4f5741
cd84c40a-6019-50c7-87f7-178668ab9c8b

Notice that we get the UUID based on the namespace and hostname.

 

Summary

This Python UUID module provides immutable UUID objects and the functions uuid1(), uuid3(), uuid4(), and  uuid5() for generating version 1, 3, 4, and 5 UUIDs. In this tutorial, we learned about all these methods by taking various examples. We also discuss the common usages of UUID in the real world. To summarize, this tutorial contains basic information about the Python UUID module and its commonly used functions.

 

Further Reading

Python UUID module
UUIDs
UUID in python

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment