Skip to content

UUID Generator — Python source

Generate RFC 4122 v4 UUIDs with crypto-grade randomness. Bulk generate, copy all, toggle format (uppercase / no hyphens).

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""RFC 4122 v4 UUID generator (cryptographically secure).

Language: Python
CosmoDev polyglot showcase port of the ``uuid`` tool.
Ported from src/lib/uuid.ts — display source, part of CosmoDev's
polyglot tool pages.

Produces a random (v4) UUID: 36 characters, lowercase, hyphenated as
8-4-4-4-12 hex digits, with the RFC version (4) and variant (10xx)
bits set.

Uses :mod:`secrets` — Python's CSPRNG module (backed by ``os.urandom`` /
the host entropy source). It is the correct primitive for any identifier
that must be unguessable; the plain :mod:`random` module is a Mersenne
Twister PRNG and must never be used for security-sensitive identifiers.
"""

from __future__ import annotations

import secrets


def uuid_v4() -> str:
    """Return a freshly generated RFC 4122 version-4 UUID string.

    Lowercase, 36 characters, e.g.
    ``"f47ac10b-58cc-4372-a567-0e02b2c3d479"``.

    The TypeScript lib short-circuits to ``crypto.randomUUID()`` when the
    platform provides it; the explicit construction below is the portable
    equivalent every language in this polyglot set implements, so the
    algorithm reads the same across all of them.
    """
    # 16 cryptographically secure random bytes from the OS CSPRNG.
    # secrets raises RuntimeError if the entropy source is unavailable —
    # the equivalent of the TypeScript lib's "no crypto" failure.
    raw = bytearray(secrets.token_bytes(16))

    # version 4: high nibble of byte 6 -> 0100
    raw[6] = (raw[6] & 0x0F) | 0x40
    # variant  : high bits of byte 8   -> 10, so the next hex digit is 8-b
    raw[8] = (raw[8] & 0x3F) | 0x80

    # bytearray.hex() renders lowercase; slice into 8-4-4-4-12 groups.
    hexed = raw.hex()
    return f"{hexed[:8]}-{hexed[8:12]}-{hexed[12:16]}-{hexed[16:20]}-{hexed[20:]}"


if __name__ == "__main__":
    print(uuid_v4())

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →