coolname

repository·master·Indexed 41 days ago

https://github.com/alexanderlukanin13/coolname

A pure Python library for generating random, human-readable strings and slugs. It provides tools for creating unique identifiers via a default generator or a customizable RandomGenerator class using rule types like words, phrases, nested, cartesian, const, and number. The library also supports loading configurations from directories or Python modules and offers a companion package, coolname-hash, for deterministic slug generation using pseudohash_slug.

Tokens
9.9K
Snippets
41
Records
51
Agent score
51%

What's inside coolname

  1. Configure word and phrase validation with word_regex and allow_whitespace

    master

    You can control how words are validated using word_regex and allow_whitespace:

    • word_regex: A regular expression used to validate all words. The default is r'\w+' (Unicode letters, numbers, and underscores).
    • allow_whitespace: If set to True, word_regex is applied only to the non-whitespace parts of the word. You can include whitespace in your regex (e.g., [a-z ]+) or keep it simple (e.g., [a-z]+) if allow_whitespace is enabled.
  2. Thread safety in coolname

    master
    The coolname module is thread-safe and virtually stateless. It relies on the global random.Random instance for its operations, which is thread-safe by design. Because of this architecture, you can safely use coolname in multi-threaded environments without additional synchronization logic.
  3. Understand parameter scopes in coolname

    master

    Parameters in coolname operate under two distinct scopes, indicated by specific icons in the documentation:

    • Configuration Scope (✅): These parameters act when a RandomGenerator is created. They are used to configure the generator or perform load-time validation. If validation fails during this phase, a ConfigurationError is raised.
    • Runtime Scope (🚀): These parameters act during every call to RandomGenerator.generate() or RandomGenerator.generate_slug(). They are used to silently discard combinations that do not meet the specified criteria (e.g., ensuring uniqueness or length constraints).
  4. Understand the precedence of generator selection

    master

    When coolname initializes, it selects a generator based on the following precedence order:

    1. COOLNAME_DATA_DIR: If defined, not empty, and the directory exists, it is used.
    2. COOLNAME_DATA_MODULE: If COOLNAME_DATA_DIR is not applicable, but this is defined and not empty, the module is imported and used.
    3. Default Generator: If neither of the above conditions are met, the built-in default generator is used.

    This hierarchy is designed to support packaging in bundles like PyInstaller. For standard usage, using COOLNAME_DATA_DIR is generally recommended as text files are easier to maintain than Python modules.

  5. How randomization works in coolname

    master

    The coolname library treats the configuration space as a virtual N-dimensional array.

    1. Calculate Combinations: It calculates the total number of possible combinations based on the configuration (e.g., using Cartesian products or nested lists).
    2. Generate Index: When calling RandomGenerator.generate_slug, the library generates a single random integer using randrange(N), where N is the total number of possible combinations.
    3. Map to Element: This integer is then used as an index to pick a specific element from the N-dimensional combination space.

    Example Calculation: Given a config with:

    • price: 2 items
    • color: 3 items
    • object: 11 items (5 from footwear + 6 from hat)

    The total combinations are $2 \times 3 \times (5 + 6) = 66$. A call to randrange(66) will map to one of these 66 unique slugs.

    import coolname
    config = {
        'all': {
            'type': 'cartesian',
            'lists': ['price', 'color', 'object']
        },
        'price': {'type': 'words', 'words': ['cheap', 'expensive']},
        'color': {'type': 'words', 'words': ['black', 'white', 'red']},
        'object': {'type': 'nested', 'lists': ['footwear', 'hat']},
        'footwear': {'type': 'words', 'words': ['shoes', 'boots', 'sandals', 'sneakers', 'socks']},
        'hat': {'type': 'phrases', 'phrases': ['top hat', 'fedora', 'beret', 'cricket cap', 'panama', 'sombrero']}
    }
    generator = coolname.RandomGenerator(config)
  6. Choosing between generate_slug and pseudohash_slug

    master

    When deciding how to generate entity slugs, choose based on your persistence requirements:

    1. Persistent Storage (Standard): Use the core coolname package's generate_slug function. Since these are random, you must store the slug in your database and use a UNIQUE constraint on the column. You must also implement logic to check for duplicates and retry generation if a collision occurs.

    2. Stateless/Deterministic (Pseudohash): Use the coolname-hash package's pseudohash_slug function if you need to derive the same slug from an entity ID every time without storing the slug itself. This is useful for lightweight, stateless applications, but you must still account for the possibility of duplicates.

  7. Configure custom generators with rule types

    master

    Configuration in coolname is a flat dictionary of rules. Each rule has a unique <rule_id> and a type. The root rule must be named 'all' to be used by generate() or generate_slug() without arguments.

    Supported rule types:

    • words: Chooses a random word from a list with equal probability.
    • phrases: Chooses a random phrase (one or more words) from a list.
    • nested: Chooses a random item from a selection of child lists. Probability is proportional to the child list length.
    • cartesian: Acts like a slot machine, producing a list by choosing one item from every child list (the Cartesian product).
    • const: Returns a fixed constant value.
    • number: Generates a random number.
    {
        '<rule_id>': {
            'comment': 'Optional info.',
            'type': '<nested|cartesian|words|phrases|const>',
            # additional fields based on type
        },
        'all': {
            'type': 'cartesian',
            'lists': ['rule1', 'rule2']
        }
    }
  8. Include coolname.data when using PyInstaller

    master

    When bundling an application into an executable using PyInstaller, you must explicitly include the coolname.data module. PyInstaller's analysis may fail to detect this dependency, leading to a ModuleNotFoundError: No module named 'coolname.data' at runtime.

    You can resolve this by using the --hidden-import flag in your CLI command or by adding the module to your PyInstaller .spec file.

    pyinstaller myscript.py --hidden-import coolname.data
  9. Generate deterministic slugs with coolname-hash

    master

    If you need to generate the same slug for a specific entity every time without storing the slug in a database, use the coolname-hash package. The pseudohash_slug function accepts integers, strings, or byte sequences and returns a deterministic slug based on that input.

    Warning: Just like random generation, this method can still produce duplicates, especially with a small number of items. Ensure your system can handle potential collisions.

    from coolname_hash import pseudohash_slug
    
    # Using an integer
    pseudohash_slug(123)
    # Returns: 'hissing-sage-buzzard-of-faith'
    
    # Using a string
    pseudohash_slug('qwerty')
    # Returns: 'jumping-kickass-bumblebee-of-chaos'
    
    # Using bytes
    pseudohash_slug(b'\x00\x01\xFF')
    # Returns: 'smooth-offbeat-hummingbird-from-avalon'
  10. Configure custom generators via environment variables

    master

    You can replace the default coolname generator by setting one or both of the following environment variables. If either is set and not empty, the default generator is not created, which saves memory.

    • COOLNAME_DATA_DIR: A path to a directory containing config.json and *.txt files.
    • COOLNAME_DATA_MODULE: A Python module name that is importable and contains a config dictionary.

    Important: If you are setting these variables within a Python script, you must set them using os.environ before importing coolname.

    import os
    # Set environment variables BEFORE importing coolname
    os.environ['COOLNAME_DATA_MODULE'] = 'some.module'
    from coolname import generate_slug
  11. Re-seed the default random generator

    master

    The coolname library uses the standard Python random module (specifically random.randrange) as its source of randomness. To re-seed the default generator used by the library, call random.seed directly. Note that coolname itself never calls random.seed.

    import os, random
    random.seed(os.urandom(128))