Generating a UUID in Python is straightforward thanks to the built-in uuid
module. Here are examples of how to generate a UUID using this module:
Basic UUID Generation
The uuid
module in Python provides functions to generate different versions of UUIDs. The most commonly used version is UUIDv4, which is randomly generated.
Example: Generating a UUID (version 4)
import uuid
# Generate a new UUID (version 4)
new_uuid = uuid.uuid4()
# Output the generated UUID
print(f"Generated UUID: {new_uuid}")
Explanation
uuid.uuid4()
: This function generates a random UUID (UUIDv4).new_uuid
: The generated UUID object.print(f"Generated UUID: {new_uuid}")
: Outputs the UUID as a string.
Running the Code
Save the code in a file, for example, generate_uuid.py
, and run it using Python:
python generate_uuid.py
Output Example
When you run the script, the output will be similar to:
Generated UUID: 123e4567-e89b-12d3-a456-426614174000
Each time you run the program, a different UUID will be generated.
Generating Different Versions of UUIDs
The uuid
module can generate other versions of UUIDs as well:
UUID Version 1 (Based on time and node)
import uuid
# Generate a new UUID (version 1)
new_uuid = uuid.uuid1()
# Output the generated UUID
print(f"Generated UUID (v1): {new_uuid}")
UUID Version 3 (Based on MD5 hash of a namespace and name)
import uuid
# Define a namespace UUID and a name
namespace_uuid = uuid.NAMESPACE_DNS
name = 'example.com'
# Generate a new UUID (version 3)
new_uuid = uuid.uuid3(namespace_uuid, name)
# Output the generated UUID
print(f"Generated UUID (v3): {new_uuid}")
UUID Version 5 (Based on SHA-1 hash of a namespace and name)
import uuid
# Define a namespace UUID and a name
namespace_uuid = uuid.NAMESPACE_DNS
name = 'example.com'
# Generate a new UUID (version 5)
new_uuid = uuid.uuid5(namespace_uuid, name)
# Output the generated UUID
print(f"Generated UUID (v5): {new_uuid}")
Summary
Here are the key steps to generate different versions of UUIDs in Python using the built-in uuid
module:
-
Generate a random UUID (version 4):
import uuid new_uuid = uuid.uuid4() print(f"Generated UUID: {new_uuid}")
-
Generate a time-based UUID (version 1):
import uuid new_uuid = uuid.uuid1() print(f"Generated UUID (v1): {new_uuid}")
-
Generate a name-based UUID (version 3, MD5):
import uuid namespace_uuid = uuid.NAMESPACE_DNS name = 'example.com' new_uuid = uuid.uuid3(namespace_uuid, name) print(f"Generated UUID (v3): {new_uuid}")
-
Generate a name-based UUID (version 5, SHA-1):
import uuid namespace_uuid = uuid.NAMESPACE_DNS name = 'example.com' new_uuid = uuid.uuid5(namespace_uuid, name) print(f"Generated UUID (v5): {new_uuid}")
These methods provide flexible options for generating different types of UUIDs in Python.