Generate UUIDs in Python
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Python
What: Generate UUIDs in Python using the built-in <code>uuid</code> module. No external dependencies required. Supports UUID1, UUID4, and UUID5.
Try it: Use our interactive Uuids generator or integrate this code into your Python application.
Generate UUIDs in Python using the built-in uuid module. No external dependencies required. Supports UUID1, UUID4, and UUID5.
Looking for other languages? Check our code examples in
PHP
,
JavaScript
,
Java
,
C#
,
C++
,
Ruby
and
Go
or use our interactive web generator.
Python Code Example
import uuid
# UUID v4 (random)
uuid4 = uuid.uuid4()
print(uuid4) # Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
print(str(uuid4)) # String representation
# UUID v1 (timestamp + MAC address)
uuid1 = uuid.uuid1()
print(uuid1) # Example: 6ba7b810-9dad-11d1-80b4-00c04fd430c8
# UUID v5 (namespaced)
namespace = uuid.NAMESPACE_DNS
name = 'example.com'
uuid5 = uuid.uuid5(namespace, name)
print(uuid5) # Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17
# Parse and validate UUID
uuid_string = '3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f'
parsed_uuid = uuid.UUID(uuid_string)
print(parsed_uuid.version) # Outputs: 4
print(parsed_uuid.hex) # Hex without dashes: 3d6f9e647d8a4c3e8f2b1a4e5c6d7e8f
# Generate multiple UUIDs
uuids = [str(uuid.uuid4()) for _ in range(5)]
print(uuids)
[EXPLANATION]
The uuid module is part of Python's standard library. UUID4 uses os.urandom() for cryptographic randomness. UUID1 includes timestamp and MAC address (less private). UUID5 is deterministic for given namespace+name.
Expected Output
3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f 6ba7b810-9dad-11d1-80b4-00c04fd430c8 cfbff0d1-9375-5685-968c-48ce8b15ae17 4 3d6f9e647d8a4c3e8f2b1a4e5c6d7e8f
Common Use Cases
- Django model primary keys
- Flask session identifiers
- PostgreSQL UUID columns
- Celery task IDs
- AWS resource tagging
- Data pipeline job identifiers
Important Notes
- UUID4 is most common (random, no privacy concerns)
- UUID1 exposes MAC address (avoid for privacy)
-
Python's
uuidmodule is thread-safe -
Convert to string with
str(uuid)
Try Our Interactive Generator
Don't want to write code? Use our free web-based Uuids generator with instant results.
TRY UUIDS GENERATOR →Other Programming Languages
View Uuids generation code examples in PHP
View Uuids generation code examples in JavaScript
View Uuids generation code examples in Java
View Uuids generation code examples in C#
View Uuids generation code examples in C++
View Uuids generation code examples in Ruby
View Uuids generation code examples in Go