Python Prefixed KSUID
PKSUID is a Python library for generating Prefixed K-Sortable Unique IDentifiers. It extends the KSUID specification by allowing an arbitrary string prefix of up to 16 bytes, similar to Stripe's prefixed IDs, which helps developers quickly identify the resource type an identifier refers to. The library is currently at version 1.1.2 and has a stable release cadence.
Common errors
-
ModuleNotFoundError: No module named 'pksuid'
cause The 'pksuid' package is not installed in your current Python environment.fixRun `pip install pksuid` to install the library. -
ValueError: Prefix length must be between 0 and 16 bytes
cause The prefix string provided when creating a `PKSUID` object exceeds the maximum allowed length of 16 bytes.fixShorten your prefix string to be 16 bytes or less. Remember that non-ASCII characters might take up more than one byte (e.g., `len('😀'.encode('utf-8'))` is 4). -
AttributeError: 'str' object has no attribute 'get_prefix'
cause You are attempting to call a method like `get_prefix()` on a string representation of a PKSUID, not on a `PKSUID` object itself.fixIf you have a PKSUID as a string (e.g., from a database or log), you must first parse it back into a `PKSUID` object using `PKSUID.parse()` before calling its methods. Example: `uid_obj = PKSUID.parse('usr_24OnhzwMpa4sh0NQmTmICTYuFaD')`.
Warnings
- gotcha PKSUID prefixes are limited to a maximum of 16 bytes. Providing a prefix longer than this will result in a `ValueError` during object instantiation.
- gotcha The `PKSUID.get_timestamp()` method returns the KSUID's internal 32-bit timestamp component, which is relative to a custom KSUID epoch (e.g., May 13th, 2014 for original KSUID specification), not the standard Unix epoch (January 1st, 1970). If you need a standard Unix timestamp or a Python `datetime` object, use `PKSUID.get_datetime()` instead.
- gotcha PKSUID objects are immutable once created. Any method that appears to 'modify' a KSUID (e.g., parsing) will return a new `PKSUID` instance rather than altering the existing one. Do not expect in-place modifications.
Install
-
pip install pksuid
Imports
- PKSUID
from pksuid import PKSUID
Quickstart
from pksuid import PKSUID
# Generate a new unique identifier with the prefix 'usr'
uid = PKSUID('usr')
print(f"Generated PKSUID: {uid}")
# Access components
print(f"Prefix: {uid.get_prefix()}")
print(f"Timestamp (KSUID epoch): {uid.get_timestamp()}")
print(f"Datetime (UTC): {uid.get_datetime()}")
print(f"Payload: {uid.get_payload()}")
# Convert from a string representation back to PKSUID
uid_from_string = PKSUID.parse('usr_24OnhzwMpa4sh0NQmTmICTYuFaD')
print(f"Parsed PKSUID: {uid_from_string}")
print(f"Parsed Datetime (UTC): {uid_from_string.get_datetime()}")
# Conversion to and parsing from bytes is also possible
uid_as_bytes = uid.bytes()
uid_from_bytes = PKSUID.parse_bytes(uid_as_bytes)
print(f"Parsed from bytes: {uid_from_bytes}")