X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=id_generator.py;h=bcd3a833270ffcd8f69f9c53f5a036d2c711566e;hb=28034f6b1df572a3a87c3bc2181f806c4e47b2eb;hp=cc287bb5819e0f31db1e504f0a136b1333f79dfe;hpb=497fb9e21f45ec08e1486abaee6dfa7b20b8a691;p=python_utils.git diff --git a/id_generator.py b/id_generator.py index cc287bb..bcd3a83 100644 --- a/id_generator.py +++ b/id_generator.py @@ -3,17 +3,35 @@ import itertools import logging +# This module is commonly used by others in here and should avoid +# taking any unnecessary dependencies back on them. + 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}") return x + + +if __name__ == '__main__': + import doctest + doctest.testmod()