Generate a UUID in Python

How to generate a UUID in Python with the standard uuid module: uuid4 for random, uuid7 for time ordered on 3.14 or with a package, uuid5 for name based, plus parsing, validation and Django and SQLAlchemy notes.

Try it here

Generate a UUID to paste into your Python code, in any version and format.

Format

Your UUIDs

Copy one, copy them all, or download the list. The format options above apply to everything shown here.

    The standard library: uuid4

    import uuid
    
    id = uuid.uuid4()        # UUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')
    str(id)                  # 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
    id.hex                   # 'f47ac10b58cc4372a5670e02b2c3d479', no hyphens
    id.bytes                 # 16 raw bytes for binary columns
    id.int                   # the 128 bit integer

    uuid4() returns a UUID object, not a string. That trips people up in JSON: json.dumps({"id": uuid.uuid4()}) raises a TypeError. Convert with str() first, or pass default=str to dumps.

    Time ordered v7

    Python 3.14 added uuid.uuid7() to the standard library, along with uuid6() and uuid8(). On older versions use a small package.

    # Python 3.14+
    uuid.uuid7()
    
    # Python 3.8 to 3.13
    pip install uuid-utils
    import uuid_utils
    uuid_utils.uuid7()       # returns a UUID compatible object
    
    # or
    pip install uuid6
    import uuid6
    uuid6.uuid7()

    Use v7 for primary keys. It sorts by creation time and keeps PostgreSQL and MySQL indexes tidy. Details on the v7 page.

    Other versions

    uuid.uuid1()                                   # time based, uses your MAC address by default
    uuid.uuid1(node=uuid.getnode() | (1 << 40))   # or pass a random node with the multicast bit
    uuid.uuid5(uuid.NAMESPACE_DNS, "example.com")  # name based, deterministic
    uuid.uuid3(uuid.NAMESPACE_URL, "https://example.com/a")

    Parse and validate

    def is_uuid(value: str) -> bool:
        try:
            uuid.UUID(value)
            return True
        except ValueError:
            return False
    
    u = uuid.UUID("{F47AC10B-58CC-4372-A567-0E02B2C3D479}")   # braces and uppercase accepted
    u.version      # 4
    u.variant      # 'specified in RFC 4122'

    The constructor is generous: it accepts braces, the urn:uuid: prefix and 32 hex characters without hyphens. If you need strict 8-4-4-4-12 input, check with a regex first, see our regex guide.

    Django and SQLAlchemy

    # Django
    class Order(models.Model):
        id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    # SQLAlchemy 2.0
    from sqlalchemy import Uuid
    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)

    Pass the function, uuid.uuid4, not a call, uuid.uuid4(). The second form generates one value at import time and every row gets the same id.

    Mistakes to avoid

    • uuid1 leaks your MAC address unless you pass a node. For anything that leaves your machine, use uuid4 or uuid7.
    • UUID objects are not strings. Compare with other UUID objects or convert both sides.
    • Do not seed random and expect unique ids. uuid4 uses os.urandom, which is correct. Rolling your own from random.getrandbits is not.

    Frequently asked questions

    How do I get a UUID as a plain string in Python?

    Wrap it in str(): str(uuid.uuid4()). For 32 characters without hyphens use .hex.

    Is uuid.uuid4() cryptographically secure?

    Yes. It reads 16 bytes from os.urandom, the operating system's secure random source, then sets the version and variant bits.

    How do I generate a UUID v7 in Python?

    On Python 3.14 or newer, uuid.uuid7(). On older versions, pip install uuid-utils or uuid6 and call uuid7() from that package.

    ↑ Top
    Copied!