Python Glossary Русский

all Python 3uuidterm

uuid.UUID

the UUID class

The class of a 128-bit unique identifier. It is built from a string, bytes or an integer; str() gives the familiar 36-character form with hyphens.

Syntax

uuid.UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None)

A UUID is not a string: uuid.UUID(s) == s is False, and json.dumps() raises TypeError, so write str(u) or u.hex explicitly when comparing or storing. The constructor accepts braces, upper case and the urn:uuid: prefix, but raises ValueError on garbage — that is how a string gets validated. version is meaningful only for the RFC 4122 variant, otherwise it is None.

Examples

import uuid
u = uuid.UUID('{6FA459EA-EE8A-3CA4-894E-DB77E160355E}')
print(u)  # → 6fa459ea-ee8a-3ca4-894e-db77e160355e
print(u.version, u == str(u), str(u) == '6fa459ea-ee8a-3ca4-894e-db77e160355e')  # → 3 False True
import uuid
try:
    uuid.UUID('xyz')
except ValueError as e:
    print(e)  # → badly formed hexadecimal UUID string
import json, uuid
u = uuid.UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
print(json.dumps({'id': str(u)}))  # → {"id": "6fa459ea-ee8a-3ca4-894e-db77e160355e"}

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy