title: Python UUID tags: - python - uuid permalink: python-uuid categories: []

date: 2017-12-16 05:14:00

Python has a built in library for generating UUIDs or as people like to call them “GUIDs”

The UUID RFC is RFC 4122.

Working with UUIDs

import uuid
# Generate UUID v1
uuid1 = uuid.uuid1()
# UUID('0e40560a-e21b-11e7-a190-185e0fcbbf2d')

# Generate UUID v3
uuid3 = uuid.uuid3(uuid.NAMESPACE_DNS, 'krisfremen.com')
# UUID('bd2e3084-88b0-31c8-b4f5-b87a2d7979bd')

# Generate UUID v4
uuid4 = uuid.uuid4()
# UUID('47019d3e-24e9-403d-8920-38cb00b97292')

# Generate UUID v5
uuid5 = uuid.uuid5(uuid.NAMESPACE_DNS, 'krisfremen.com')
# UUID('ca124f80-2e9d-59e9-b8ab-15bd81ff891d')

# Parse UUID string into a UUID object
# It ignores any hyphens or braces
uuidparse = uuid.UUID('{00000000-0000-0000-0000-000000000000}')
# UUID('00000000-0000-0000-0000-000000000000')

# String representation of a standard form UUID
uuidstr = str(uuid3)
# 'bd2e3084-88b0-31c8-b4f5-b87a2d7979bd'

# Hex representation of UUID (No hyphen string)
uuidhex = uuid3.hex
# 'bd2e308488b031c8b4f5b87a2d7979bd'

# Raw bytes of UUID
uuidbytes = uuid3.bytes
# b'\xbd.0\x84\x88\xb01\xc8\xb4\xf5\xb8z-yy\xbd'

# UUID from bytes
uuidfromybytes = uuid.UUID(bytes=uuidbytes)
# uuidfromybytes = uuid.UUID(bytes=uuidbytes)

UUID Variant specifics

Every UUID variant has different characteristics

UUID 1

UUID Variant 1 uses the current time and includes the MAC address of the device.

UUID 2

UUID Variant 2 is a reserved variant which is the exact same as UUID1 except the variant bit is two and reserved for Microsoft.

UUID 3

UUID Variant 3 is an MD5 hash of a namespace and a name.

UUID 4

UUID Variant 4 is random.

UUID 5

UUID Variant 3 is an SHA-1 hash of a namespace and a name.

UUID 3 and 5 Namespaces

The default namespaces defined in the RFC are as follows :

DNS = UUID(‘6ba7b810-9dad-11d1-80b4-00c04fd430c8’)

URL = UUID(‘6ba7b811-9dad-11d1-80b4-00c04fd430c8’)

OID = UUID(‘6ba7b812-9dad-11d1-80b4-00c04fd430c8’)

X500 = UUID(‘6ba7b814-9dad-11d1-80b4-00c04fd430c8’)

One liner

python -c 'import uuid; print(uuid.uuid4())'