Before going ahead and describing how we can use Python to create a universally unique identifier (UUID), one might ask, what is the UUID anyway? So, let's start by defining what we mean by a UUID and why we use it.
What Is a UUID?
The UUID is basically a 16-byte (128-bit) number used to uniquely identify an object (data). This number consists of 32 hexadecimal digits which are displayed in five groups, and separated by hyphens. To see what a UUID might look like, here is an example:
The goal of using such an identifier is to guarantee that we don't have similar identifiers, or at least guarantee having an identifier to be different from any UUIDs generated until 3400 A.D.!
Such uniqueness is achieved by combining different components together that would guarantee that UUIDs are different. The identifier in this case will be composed of the network address of the machine, a timestamp, and a randomly generated component.
Thus, we can say that a UUID is considered an algorithm which is used to create a unique string of particular format which is composed of different components that ensure the uniqueness of the identifier.
UUIDs in Python
Let's now come to the fun part, how to create a UUID in python. In order to do so, we will need to use Python's uuid module. You don't need to install anything at this point, as this module comes with your Python distribution. All you need to do to use the module is to import it directly from your script. Before that, let me show you how Python's documentation describes this module:
This module provides immutable
UUIDclass) and the functions
uuid5()for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.
Well, guess what? As we learned in the smooth refreshers series, Python strives to make things easy, and creating a UUID is no different. Here you go!
import uuid print uuid.uuid4()
Yes, that's it! This is all you need to generate a UUID in Python. On my machine, I got the following output:
How many hexadecimal digits can you see?
Don't you think Python is trying to make our lives easier?!