Generate a UUID in Python

Python is a very popular, interpreted, dynamically typed, object-oriented programming language.

First released in 1991 by Guido van Rossum, Python makes use of indentation and whitespace to delimit different blocks of code. It is a general-purpose language and as such is used in many different contexts including (to name just a few) web applications and artificial intelligence.

How to Generate a UUID in Python

The Python language has built-in support for generating Version 1, 3, 4 and 5 UUIDs. Here’s an example of how you can create a Version 4 UUID in Python code.

import uuid

myuuid = uuid.uuid4()

print('Your UUID is: ' + str(myuuid))

Explanation

  • On line #1, we import Python’s built-in uuid module.

  • On line #3, we generate a new Version 4 UUID using the uuid module and store it in the variable, myuuid. This is an instance of Python’s UUID class, not a string.

  • On line #5, we use Python’s function, str, to convert from the UUID object to a string.

  • The output from line #5 will be something like:

    Your UUID is: c303282d-f2e6-46ca-a04a-35d3d873712d

Python’s uuid module has a number of other functions, such as for generating other UUID versions (i.e. 1, 3, 4, and 5). An instance of the Python UUID class has a number of useful methods on it, such as for converting the UUID to bytes, or for converting to a 32 character string (i.e. normal UUID without the ‘-’ characters).

Convert from a String to a UUID

Although it’s rare, in some circumstances you might need to convert from a string (like the one generated on line #5 above) or byte representation of a UUID back into an instance of UUID.

Python’s uuid module provides for this scenario with the constructor method, uuid.UUID. You can call this method like this:

import uuid

myuuid = uuid.uuid4()
myuuidStr = str(myuuid)

sameMyUuid = uuid.UUID(myuuidStr)
assert myuuid == sameMyUuid

Explanation

  • Line #3 generates a new Version 4 UUID.
  • Line #4 converts the UUID instance into a string, using the str function.
  • Line #6 converts the string representation of a UUID into a Python UUID instance (sameMyUuid) using the uuid.UUID() method. Note that this method accepts a number of different formats, including strings and bytes.
  • Line #7 is included to show that the 2 UUID instances are equal.

How can we improve this page? Let us know!