X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=id_generator.py;h=dc2ac9cc810a4e1d588d60231371e873d9d31966;hb=89f305d67e913ea1512e2618a0375359ec925ada;hp=c5a0d93e6908838c1f382b386a64957f3c2ea3fc;hpb=09e6d10face80d98a4578ff54192b5c8bec007d7;p=python_utils.git diff --git a/id_generator.py b/id_generator.py index c5a0d93..dc2ac9c 100644 --- a/id_generator.py +++ b/id_generator.py @@ -1,5 +1,8 @@ #!/usr/bin/env python3 +"""A helper class for generating thread safe monotonically increasing +id numbers.""" + import itertools import logging @@ -10,13 +13,29 @@ logger = logging.getLogger(__name__) generators = {} -def get(name: str) -> int: +def get(name: str, *, start=0) -> int: """ - def __init__(self): - self.my_unique_id = id_generator.get("student_id") + Returns a thread safe monotonically increasing id suitable for use + as a globally unique identifier. + + >>> import id_generator + >>> id_generator.get('student_id') + 0 + >>> id_generator.get('student_id') + 1 + >>> id_generator.get('employee_id', start=10000) + 10000 + >>> id_generator.get('employee_id', start=10000) + 10001 """ if name not in generators: - generators[name] = itertools.count() + generators[name] = itertools.count(start, 1) x = next(generators[name]) - logger.debug(f"Generated next id {x}") + logger.debug("Generated next id %d", x) return x + + +if __name__ == '__main__': + import doctest + + doctest.testmod()