Skip to content
shellhacks.dev
Python

Generate a UUID

Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.

2 min read
Summarize in AI

A record needs an identifier that nobody has to coordinate, and sometimes the same input must always give the same one.

Python
import uuid

u = uuid.uuid4()
print(len(str(u)), u.version, len(u.hex))
print(uuid.uuid4() == uuid.uuid4())
print(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))
print(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com") == uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))
print(uuid.UUID("CFBFF0D1-9375-5685-968C-48CE8B15AE17"))
Text
36 4 32
False
cfbff0d1-9375-5685-968c-48ce8b15ae17
True
cfbff0d1-9375-5685-968c-48ce8b15ae17

uuid4 fills the identifier with 122 random bits from os.urandom, so collisions are not a practical concern and no state is shared between machines. uuid5 hashes a namespace and a name with SHA-1, so the same pair always returns the same value, which suits deriving a stable ID from a URL or an email. The module is described in the uuid documentation. str gives the hyphenated text and hex the 32 characters without hyphens, and a parsed value is normalized to lowercase.

uuid1 embeds the MAC address and a timestamp, which leaks both, so prefer uuid4. A random UUID has no order, which makes it a poor primary key for a B-tree index that wants sequential inserts. Python 3.14 added uuid7 for time-ordered values. UUIDs are identifiers, not secrets; use the secrets module for tokens.

Taggedpython
Share

More snippets

Python

Read a CSV file

Read a CSV file with csv.reader and open it with newline=''. Without that argument a line break inside a quoted field is changed before the parser sees it.

2 min read
Python

Convert a timestamp

Convert a Unix timestamp with datetime.fromtimestamp(ts, tz=timezone.utc). Without tz it uses the machine's zone, and milliseconds need a division by 1000.

1 min read
Python

Base64 encode a string

Encode with base64.b64encode(), which takes and returns bytes, so encode the string first and decode the result. The URL-safe variant swaps two characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.