runid.py 1016 B

123456789101112131415161718192021222324252627282930
  1. """runid util."""
  2. import random
  3. import secrets
  4. from string import ascii_lowercase, digits
  5. _ID_CHARS = f"{ascii_lowercase}{digits}"
  6. # Create a dedicated Random instance with its own state so it
  7. # is not affected by global random.seed() calls
  8. _random = random.Random()
  9. def generate_id(length: int = 8) -> str:
  10. """Generate a random base-36 string of `length` digits."""
  11. # There are ~2.8T base-36 8-digit strings. If we generate 210k ids,
  12. # we'll have a ~1% chance of collision.
  13. return "".join(secrets.choice(_ID_CHARS) for _ in range(length))
  14. def generate_fast_id(length: int = 8) -> str:
  15. """Faster alternative to `generate_id` if cryptographic strength isn't needed.
  16. In local testing at the time of implementation, this is ~30-50x faster than
  17. `generate_id` when generating 128-character IDs.
  18. Uses a dedicated Random instance to avoid being affected by global
  19. random.seed() calls from user code or libraries.
  20. """
  21. return "".join(_random.choices(_ID_CHARS, k=length))