Timestamp-orderable UUIDs for Python, written in Rust.

Related tags

Command-line uuidt
Overview

UUIDT

Timestamp-orderable UUIDs for Python, written in Rust.

Installation

pip install uuidt

Usage

import uuidt

# Create a new UUIDT
u = uuidt.new('my-namespace')

# Print the UUIDT properties
print(u.namespace)
print(u.timestamp)
print(u.hostname)
print(u.random_chars)

# Convert to a string
print(str(u))

# Extract the timestamp from a UUIDT string
print(uuidt.extract_timestamp("cr3su3qh-4ium-00bk-00ip-vqlpgpomk3dv"))
# 1678562753992474990

Motivation

UUIDs are great for generating unique identifiers, but they are not necessarily time-orderable. This is a problem if you want to generate a UUID for a new record in a database, and then use that UUID to order the records by creation time.

Many databases avoid this problem using auto-incrementing integer IDs, but this isn't possible in distributed databases like CockroachDB, so a UUID is typically used as the primary key instead.

This library generates UUIDs that are time-orderable. The first 12 alphanumeric characters of the UUID are a nanosecond-precision timestamp which has been base-36 encoded, so they can be sorted lexicographically. The remaining 20 characters are a combination of a namespace, the hostname of the machine that generated the UUID, and a random string.

Technically, UUID1s are also time-orderable, but they are not guaranteed to be ordered by creation time, and it can be difficult to extract the timestamp from a UUID1.

Why Rust?

Mostly as a learning opportunity for me, though also for speed. The Rust implementation is significantly faster than the Python implementation, which used Numpy to convert to base-36.

What if I don't want the Rust implementation?

UUIDT should be installable as a wheel on most systems, but if you hate Ferris and want to use the Python implementation instead, here's some equivalent code:

import random
import socket
import time

import numpy as np

BASE = 36
DIVISOR = BASE - 1
CHARACTERS = list('0123456789abcdefghijklmnopqrstuvwxyz')[:BASE]


class UUIDT:
    def __init__(self, namespace: str, timestamp: int, hostname: str, random_chars: str):
        self.namespace = namespace
        self.timestamp = timestamp
        self.hostname = hostname
        self.random_chars = random_chars

    def __str__(self):
        hostname_enc = sum(self.hostname.encode('utf-8'))
        namespace_enc = sum(self.namespace.encode('utf-8'))

        timestamp_str = np.base_repr(self.timestamp, 36).lower()
        hostname_str = np.base_repr(hostname_enc, 36).lower()
        namespace_str = np.base_repr(namespace_enc, 36).lower()

        return (
            f'{timestamp_str[:8]}-{timestamp_str[8:]}-{hostname_str:0>4}-'
            f'{namespace_str:0>4}-{self.random_chars}'
        )


def new(namespace: str) -> UUIDT:
    timestamp = time.time_ns()
    hostname = socket.gethostname()
    random_chars = ''.join(random.choices(CHARACTERS, k=4))

    return UUIDT(namespace, timestamp, hostname, random_chars)

License

MIT

Using UUIDT in your project

While UUIDT is MIT licensed, I'm really curious to seeing the projects that use it! If you use UUIDT in your project, I'd love to hear about it! Please let me know by either opening an issue or sending me an email at the address in the pyproject.toml file.

Contributing

Contributions are welcome! Just open an issue or a pull request.

You might also like...
python dependency vulnerability scanner, written in Rust.
python dependency vulnerability scanner, written in Rust.

🐍 Pyscan A dependency vulnerability scanner for your python projects, straight from the terminal. 🚀 blazingly fast scanner that can be used within l

Python wrapper around reth db. Written in Rust.

reth-db-py Bare-bones Python package allowing you to interact with the Reth DB via Python. Written with Rust and Pyo3. This python wrapper can access

A simple CLI tool to create python project file structure, written in Rust
A simple CLI tool to create python project file structure, written in Rust

Ezpie Create python projects blazingly fast What Ezpie can do? It can create a python project directory What kind of directory can Ezpie create? For c

The fastest memoizing and caching Python library written in Rust.

Cachebox Cachebox is a Python library (written in Rust) that provides memoizations and cache implementions with different cache replecement policies.

Python package for topological data analysis written in Rust. Not limited to just H0 and H1.

Topological Data Analysis (TDA) Contents Installation Compiling from source Roadmap TDA is a python package for topological data analysis written in R

My solutions for the Advent of Code 2021 in Scala, Python, Haskell and Rust.

Advent of Code 2021 These are my Advent of Code 2021 solutions written in Scala 3, Haskell, Python and Rust. Day Title L1 L2 L3 L4 01 Sonar Sweep Scal

A toy example showing how to run Rust code in Python for speed and progress.

PoC: Integrating Rust in Python A toy example showing how to run Rust code in Python for speed and progress. Requirements Python 3.6+ Rust 1.44+ Cargo

Rust implementation of Python command line progress bar tool tqdm.
Rust implementation of Python command line progress bar tool tqdm.

tqdm Rust implementation of Python command line progress bar tool tqdm. From original documentation: tqdm derives from the Arabic word taqaddum (تقدّم

Python/Rust implementations and notes from Proofs Arguments and Zero Knowledge study group

What is this? This is where I'll be collecting resources related to the Study Group on Dr. Justin Thaler's Proofs Arguments And Zero Knowledge Book. T

Releases(v0.1.1)
Owner
Isaac Harris-Holt
Technology journalist and content creator. Avid Pythonista and hopefully future billionaire.
Isaac Harris-Holt
Generate and translate standard uuids into shorter formats and back.

short-uuid Generate and translate standard UUIDs into shorter or just different formats and back. A port of the JavaScript npm package short-uuid so b

Radim Höfer 3 Feb 28, 2024
Rust Imaging Library's Python binding: A performant and high-level image processing library for Python written in Rust

ril-py Rust Imaging Library for Python: Python bindings for ril, a performant and high-level image processing library written in Rust. What's this? Th

Cryptex 13 Dec 6, 2022
Fast DNA manipulation for Python, written in Rust.

quickdna Quickdna is a simple, fast library for working with DNA sequences. It is up to 100x faster than Biopython for some translation tasks, in part

Secure DNA 22 Dec 31, 2022
This is a simple command line application to convert bibtex to json written in Rust and Python

bibtex-to-json This is a simple command line application to convert bibtex to json written in Rust and Python. Why? To enable you to convert very big

null 3 Mar 23, 2022
Fuzzy Index for Python, written in Rust. Works like error-tolerant dict, keyed by a human input.

FuzzDex FuzzDex is a fast Python library, written in Rust. It implements an in-memory fuzzy index that works like an error-tolerant dictionary keyed b

Tomasz bla Fortuna 8 Dec 15, 2022
📦 A Python package manager written in Rust inspired by Cargo.

huak About A Python package manager written in Rust. The Cargo for Python. ⚠️ Disclaimer: huak is currently in its proof-of-concept (PoC) phase. Huak

Chris Pryer 186 Jan 9, 2023
📦 A Python package manager written in Rust inspired by Cargo.

huak About A Python package manager written in Rust. The Cargo for Python. ⚠️ Disclaimer: huak is currently in its Alpha phase. Huak aims to support a

Chris Pryer 161 Oct 9, 2022
An extremely fast Python linter, written in Rust.

Ruff An extremely fast Python linter, written in Rust. Linting the CPython codebase from scratch. ⚡️ 10-100x faster than existing linters ?? Installab

Charlie Marsh 5.1k Dec 30, 2022
⚡ Blazing fast async/await HTTP client for Python written on Rust using reqwests

Reqsnaked Reqsnaked is a blazing fast async/await HTTP client for Python written on Rust using reqwests. Works 15% faster than aiohttp on average RAII

Yan Kurbatov 8 Mar 2, 2023
A Python package written in Rust for email verification without sending any emails.

PyRustify PyRustify is a Python package written in Rust that verifies the email addresses. Features Feature Description Syntax validation Checks if th

Mng 8 Apr 16, 2023