uuid.UUID

Exactly one of hex, bytes, bytes_le, fields or int. The hex string may have braces, a urn:uuid: prefix, hyphens anywhere and any case; what is left must be 32 characters that int(..., 16) accepts. version= overwrites the version and variant bits.

uuid classPython 2.5+ (is_safe 3.7+)Live demo
Common call
uuid.UUID('12345678-1234-5678-1234-567812345678')
Returns
UUID('12345678-1234-5678-1234-567812345678')
Replaces
Regex validation of UUID strings
Watch out
A UUID never == its string; compare str(u) or parse both
uuid.UUID(hexhex — 32 hex digits; 'urn:' and 'uuid:' are removed anywhere, '{' and '}' stripped from the ends, every '-' removed. Positional.type: str · default: None=None, bytesbytes — 16 bytes, big-endian (the network order of the six fields).type: bytes · default: None=None, bytes_lebytes_le — 16 bytes with the first three fields little-endian (the Microsoft GUID layout).type: bytes · default: None=None, fieldsfields — (time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node): 32, 16, 16, 8, 8 and 48 bits.type: tuple[int, ...] · default: None=None, intint — The whole UUID as an int from 0 to 2**128 - 1.type: int · default: None=None, versionversion — 1 to 5 in 3.13: sets the variant to RFC 4122 and the version nibble, overriding those bits of the input.type: int · default: None=None, *, is_safeis_safe — Keyword-only; stored as the is_safe attribute (3.7+).type: SafeUUID · default: SafeUUID.unknown=SafeUUID.unknown)
→ uuid.UUID

Demo

Live evaluation
Every accepted spelling gives the same UUID; the repr shows the canonical form.
Try:
Inputs
textstra UUID string
Code
import uuid
uuid.UUID('{12345678-1234-5678-1234-567812345678}')
Result
UUID('12345678-1234-5678-1234-567812345678')

The parser does not check where hyphens are: it deletes all of them. It also does not strip whitespace, so a trailing space makes 33 characters and "badly formed hexadecimal UUID string". With exactly 32 characters the final step is int(text, 16), so a non-hex digit fails with int's message instead. In the compare tab the two spellings are equal UUIDs, but str(a) only equals the lowercase canonical text.

Parameters

NameTypeRequiredDescription
hexstrno (None)32 hex digits; 'urn:' and 'uuid:' are removed anywhere, '{' and '}' stripped from the ends, every '-' removed. Positional.
bytesbytesno (None)16 bytes, big-endian (the network order of the six fields).
bytes_lebytesno (None)16 bytes with the first three fields little-endian (the Microsoft GUID layout).
fieldstuple[int, ...]no (None)(time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node): 32, 16, 16, 8, 8 and 48 bits.
intintno (None)The whole UUID as an int from 0 to 2**128 - 1.
versionintno (None)1 to 5 in 3.13: sets the variant to RFC 4122 and the version nibble, overriding those bits of the input.
is_safeSafeUUIDno (SafeUUID.unknown)Keyword-only; stored as the is_safe attribute (3.7+).

Return value

uuid.UUID — An immutable, hashable UUID holding one 128-bit integer.

Attributes

AttributeTypeMeaning
uuid.int_typeModule-level alias of the built-in int. The class body defines properties named int and bytes, so uuid.py keeps int_ and bytes_ to reach the built-ins. Not documented; do not use it.
uuid.bytes_typeModule-level alias of the built-in bytes, for the same reason.

Common patterns

Parse or reject
Strip first: text read from files and forms often ends in whitespace.
import uuid
def parse_uuid(text):
    try:
        return uuid.UUID(text.strip())
    except ValueError:
        return None
Strict canonical check
UUID() is lenient. Compare with the canonical string to accept only the 8-4-4-4-12 form.
import uuid
def is_canonical(text):
    try:
        return str(uuid.UUID(text)) == text
    except ValueError:
        return False
UUIDs as dict keys
Hashable and equal by value, so parsed keys find each other whatever the input spelling.
import uuid
by_id = {uuid.UUID(row['id']): row for row in rows}
by_id[uuid.UUID(request_id)]

Examples

1. Five constructor forms, one UUID
import uuid forms = [ uuid.UUID('{12345678-1234-5678-1234-567812345678}'), uuid.UUID(bytes=bytes.fromhex('12345678123456781234567812345678')), uuid.UUID(bytes_le=bytes.fromhex('78563412341278561234567812345678')), uuid.UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)), uuid.UUID(int=0x12345678123456781234567812345678), ] len(set(forms))
Returns
1
2. repr and str
import uuid u = uuid.UUID(int=1) (repr(u), str(u))
Returns
("UUID('00000000-0000-0000-0000-000000000001')", '00000000-0000-0000-0000-000000000001')
3. Sorts by its int value
import uuid sorted([uuid.UUID(int=3), uuid.UUID(int=1)])
Returns
[UUID('00000000-0000-0000-0000-000000000001'), UUID('00000000-0000-0000-0000-000000000003')]
4. Works as a dict key
import uuid {uuid.UUID(int=1): 'a'}[uuid.UUID('00000000-0000-0000-0000-000000000001')]
Returns
'a'
5. int() gives the 128-bit value
import uuid int(uuid.UUID(int=255))
Returns
255
6. Immutable
import uuid u = uuid.UUID(int=1) u.int = 2
Returns
TypeError: UUID objects are immutable
7. Ordering with a str fails
import uuid uuid.UUID(int=1) < '2'
Returns
TypeError: '<' not supported between instances of 'UUID' and 'str'
8. int_ and bytes_ are the built-ins
import uuid (uuid.int_ is int, uuid.bytes_ is bytes)
Returns
(True, True)

Pitfalls

1. Passing the UUID text as bytes
The first positional argument is hex, a str. b"..." text there fails inside str.replace; bytes= expects the 16 raw bytes, not the 32 hex characters.
UUID(b"...")
import uuid
uuid.UUID(b'12345678123456781234567812345678')
TypeError: a bytes-like object is required, not 'str'
decode first
import uuid
uuid.UUID(b'12345678123456781234567812345678'.decode())
UUID('12345678-1234-5678-1234-567812345678')
2. Calling UUID() with no argument
There is no default: an empty UUID does not exist. For a new random one call uuid4(); for all zeros pass int=0.
UUID()
import uuid
uuid.UUID()
TypeError: one of the hex, bytes, bytes_le, fields, or int arguments must be given
int=0
import uuid
uuid.UUID(int=0)
UUID('00000000-0000-0000-0000-000000000000')
3. Whitespace around the text
Hyphens and braces are removed, whitespace is not. A trailing newline from a file makes the string the wrong length.
raw line
import uuid
uuid.UUID('12345678-1234-5678-1234-567812345678\n')
ValueError: badly formed hexadecimal UUID string
.strip()
import uuid
uuid.UUID('12345678-1234-5678-1234-567812345678\n'.strip())
UUID('12345678-1234-5678-1234-567812345678')

When to use

Use it
  • Parsing and validating UUIDs from text, bytes or database ints
  • Storing IDs as objects that compare, sort and hash by value
Reach for something else
  • Making a new ID → uuid4() (or uuid5() from a name)
  • Strict format checking → compare with str(uuid.UUID(s)), since the parser is lenient

Notes

CPython impl
class UUID in Lib/uuid.py: __slots__ = ('int', 'is_safe', '__weakref__'); __setattr__ always raises, __init__ sets the slots with object.__setattr__
Parsing
hex.replace('urn:', '').replace('uuid:', ''), then .strip('{}').replace('-', ''), then len() == 32 and int(hex, 16). That last step is why int's rules leak through: on 3.13 a leading '0x', '+' or whitespace inside the 32 characters is accepted
Comparison
==, <, <=, >, >= compare the int values of two UUIDs; with any other type == is False and ordering raises TypeError. hash(u) == hash(u.int)
bytes check
UUID(bytes=...) verifies the type with assert isinstance(bytes, bytes_), so a 16-character str gives AssertionError; under python -O the assert is skipped and int.from_bytes raises "TypeError: cannot convert 'str' object to bytes" instead

FAQ

uuid.UUID(s). It accepts the canonical form, braces, a urn:uuid: prefix, missing hyphens and upper case, and raises ValueError otherwise.