Utils

Unique ID Factory

This is a detailed and didactic documentation of the IDGenerator class, designed to give a clear view of its capabilities and internal workings.

On this page

    #Overview

    The IDGenerator class is a robust utility tool developed in Python for creating unique identifiers. In software systems, choosing the right ID is crucial: some need to be sortable in time (like logs), others need to be impossible to guess (like password recovery tokens) and others need to follow specific business formats (like service protocols).

    This class centralizes those needs in a simple interface, using standard Python libraries focused on security (secrets) and uniqueness (uuid).

    #Execution Flow

    The class's workflow is based on the Static Utility pattern. Since all methods are decorated with @classmethod, you do not need to instantiate the class (do gen = IDGenerator()) to use it.

    1. Method Call: The user requests a type of ID (e.g. IDGenerator.token()).
    2. Input Validation: The method checks whether the parameters (such as length or version) are valid.
    3. Processing/Generation:
      • For UUIDs, it queries the uuid module.
      • For Timestamps, it captures the time in nanoseconds (time.time_ns()).
      • For Custom/Tokens, it uses secrets to pick random characters in a cryptographically secure way.
    4. Return: The identifier is formatted as a string and returned to the caller.

    #Methods Table

    MethodMain PurposeKey Feature
    uuid(version)Universal unique identification.RFC 4122 standard (128 bits).
    timestamp(...)IDs that follow a chronological order.Based on nanoseconds + random suffix.
    token(len, safe)Security and authentication.Cryptographically strong and URL-safe.
    custom(pattern)Identifiers with business rules.Uses masks to define numbers and letters.

    #Architecture and Insights

    • Cryptographic Security: Using secrets instead of random ensures that the IDs generated for tokens cannot be predicted by brute-force attacks or statistical analysis.
    • High Granularity: By using time.time_ns() in the timestamp method, the chance of collision (two identical IDs generated at the same time) is drastically reduced, since the precision is billionths of a second.
    • Flexibility through Masks: The custom method works as a "Mini-Template Engine", allowing developers to create formats such as NF-2024-#### without having to rewrite random generation logic.

    #Technical Details

    #IDGenerator Class

    Description

    A utility class of class methods aimed at generating identification strings. It requires no internal state and focuses on the purity of the generation functions.

    Arguments

    The class itself takes no initialization arguments (it is a static class).

    Methods

    #1. uuid

    Description: Generates a Universally Unique Identifier (UUID). It is the best choice for primary keys in distributed databases.

    Arguments:

    • version (int): The UUID version. Supports 1 (time + MAC address) or 4 (fully random). Default: 4.

    Returns:

    • str: The formatted UUID (e.g. 8f3...).

    Raises:

    • ValueError: If the given version is different from 1 or 4.

    Examples:

    IDGenerator.uuid(version=4) # '784a0d9b-2b41-4c12-8877-6f8d92305381'

    #2. timestamp

    Description: Creates an ID based on the exact moment of execution. Excellent for logs and systems where creation order matters.

    Arguments:

    • prefix (str): Initial text.
    • separator (str): Joining character.
    • as_hex (bool): If True, converts the time to hexadecimal base (shorter).
    • suffix_len (int): Number of extra random characters at the end to avoid collisions.

    Returns:

    • str: Formatted temporal string.

    Raises:

    • ValueError: If suffix_len is negative.

    Examples:

    IDGenerator.timestamp(prefix="PEDIDO", separator="-", as_hex=True)
    # 'PEDIDO-18f74d0a2bc5f1a39aB3'

    #3. token

    Description: Generates a secure random sequence. Recommended for temporary passwords, API keys and session tokens.

    Arguments:

    • length (int): Length of the string.
    • url_safe (bool): If True, removes characters that can cause errors in URLs (such as + or /).

    Returns:

    • str: Random token.

    Raises:

    • ValueError: If length is less than or equal to zero.

    Examples:

    IDGenerator.token(length=12, url_safe=True) # 'kL9_zP2mNx8A'

    #4. custom

    Description: Generates an ID following a visual template (mask) defined by the user.

    Arguments:

    • pattern (str): String containing the markers # (number), ? (letter) or (both).

    Returns:

    • str: String formatted according to the pattern.

    Raises:

    • ValueError: If the pattern is empty.

    Examples:

    IDGenerator.custom("PLA-####-??") # 'PLA-5521-XW'

    Source: src/utils/unique_id_factory.py

    Esc
    ↑↓navigate Enteropen