ULID Python Implementation (ahawker/ulid)
The `ulid-py` library (version 1.1.0) provides a minimal, self-contained Python 3 implementation of the Universally Unique Lexicographically Sortable Identifier (ULID) specification. It aims for a lightweight implementation without external dependencies. The project is currently in maintenance mode, with its last release in March 2022.
Warnings
- breaking Python 2 support was dropped in version 1.0.0. This library (v1.1.0) requires Python 3.5 or newer.
- gotcha Potential confusion with other Python ULID libraries. While this entry is for `ulid-py` (ahawker's implementation), there are other popular and more actively maintained libraries like `python-ulid` (mdomke's implementation) with different APIs (e.g., `ULID()` constructor vs. `ulid.new()`).
- gotcha API differences for accessing ULID components. In `ulid-py` (ahawker), `timestamp()` and `randomness()` are methods. In some other ULID libraries, these might be properties (e.g., `ulid.timestamp`).
- gotcha Security considerations when using ULIDs. Although `ulid-py` does not explicitly implement monotonic incrementing of the random component for same-millisecond generation by default (based on available documentation for this specific library), the timestamp component of ULIDs can still expose creation times. For applications requiring strong unpredictability (e.g., password reset tokens), a cryptographically secure random identifier might be more appropriate.
Install
-
pip install ulid-py
Imports
- new
import ulid ulid.new()
- from_timestamp
import ulid ulid.from_timestamp(some_datetime_obj)
- from_uuid
import ulid ulid.from_uuid(some_uuid_obj)
Quickstart
import ulid
import datetime
# Create a brand new ULID
u = ulid.new()
print(f"New ULID: {u}")
print(f"String representation: {str(u)}")
# Create a new ULID from an existing datetime object
dt = datetime.datetime(1999, 1, 1, tzinfo=datetime.timezone.utc)
u_from_dt = ulid.from_timestamp(dt)
print(f"ULID from datetime: {u_from_dt}")
# Access timestamp and randomness parts
print(f"Timestamp part: {u.timestamp()}")
print(f"Randomness part: {u.randomness()}")
# Convert to UUID
import uuid
uuid_val = u.to_uuid()
print(f"As UUID: {uuid_val}")