X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=id_generator.py;h=4b61a93081d6dd17ab341330e7d4f08991ad4aab;hb=02302bbd9363facb59c4df2c1f4013087702cfa6;hp=4e650dca9f13662a1ace7013d4f00bcd3a0082e2;hpb=709370b2198e09f1dbe195fe8813602a3125b7f6;p=python_utils.git diff --git a/id_generator.py b/id_generator.py index 4e650dc..4b61a93 100644 --- a/id_generator.py +++ b/id_generator.py @@ -1,5 +1,12 @@ #!/usr/bin/env python3 +# © Copyright 2021-2022, Scott Gasch + +"""A helper class for generating thread safe monotonically increasing +id numbers. + +""" + import itertools import logging @@ -10,9 +17,9 @@ logger = logging.getLogger(__name__) generators = {} -def get(name: str) -> int: +def get(name: str, *, start=0) -> int: """ - Returns a thread safe monotonically increasing id suitable for use + Returns a thread-safe, monotonically increasing id suitable for use as a globally unique identifier. >>> import id_generator @@ -20,14 +27,19 @@ def get(name: str) -> int: 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()