uuid

The Python uuid module provides a way to generate universally unique identifiers (UUIDs), which are 128-bit values used to uniquely identify information in computer systems. UUIDs are often used when a unique identifier is required, such as database keys or session IDs.

Here’s a quick example:

Python
>>> import uuid

>>> uuid.uuid4()
UUID('12345678-1234-5678-1234-567812345678')

Key Features

  • Generates UUIDs using random, time-based, and name-based methods
  • Supports UUID versions 1, 3, 4, and 5
  • Parses and validates UUID strings and objects
  • Converts UUIDs to and from string representations
  • Integrates seamlessly with Python types and serialization
  • Guarantees uniqueness across space and time

Frequently Used Classes and Functions

Object Type Description
uuid.UUID Class Represents a UUID object
uuid.uuid1() Function Generates a UUID based on the host ID and current time
uuid.uuid3() Function Generates a name-based UUID using MD5 hashing
uuid.uuid4() Function Generates a random UUID
uuid.uuid5() Function Generates a name-based UUID using SHA-1 hashing
uuid.getnode() Function Returns the hardware address as a 48-bit integer
uuid.NAMESPACE_DNS Class Represents the DNS namespace constant for name-based UUIDs

Examples

Generating a name-based UUID using MD5 hashing:

Python
>>> import uuid

>>> uuid.uuid3(uuid.NAMESPACE_DNS, "python.org")
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

Common Use Cases

  • Generating unique identifiers for database entries
  • Creating unique session IDs for web applications
  • Ensuring uniqueness of identifiers in distributed systems
  • Tagging files, resources, or objects with unique IDs
  • Safely merging data from multiple sources
  • Implementing resource identifiers in network protocols
  • Supporting object tracking in logging or auditing systems

Real-World Example

Here’s an example of using the uuid module to generate a unique filename for an uploaded file in a web application. This approach helps prevent filename collisions:

Python
>>> import uuid

>>> def generate_unique_filename(filename):
...     file_extension = filename.split(".")[-1]
...     unique_id = uuid.uuid4()
...     return f"{unique_id}.{file_extension}"
...

>>> generate_unique_filename("document.txt")
'3f6d2f0e-19a4-4e5b-8cb3-3c9b7f2c9db7.txt'

In this example, the uuid module generates a UUID to ensure that each uploaded file has a unique name, preventing any potential file overwrites.