Python Prefixed KSUID

1.1.2 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This example demonstrates how to generate a new PKSUID with a specified prefix, extract its components like prefix, timestamp, and datetime, and parse a PKSUID from its string or byte representation.

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}")

view raw JSON →