X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=src%2Fpyutils%2Fid_generator.py;h=7d2e151addc17399efbea6bc6196d598c7bb6543;hb=HEAD;hp=4b61a93081d6dd17ab341330e7d4f08991ad4aab;hpb=69566c003b4f1c3a4905f37d3735d7921502d14a;p=pyutils.git diff --git a/src/pyutils/id_generator.py b/src/pyutils/id_generator.py index 4b61a93..7d2e151 100644 --- a/src/pyutils/id_generator.py +++ b/src/pyutils/id_generator.py @@ -1,10 +1,15 @@ #!/usr/bin/env python3 -# © Copyright 2021-2022, Scott Gasch +# © Copyright 2021-2023, Scott Gasch -"""A helper class for generating thread safe monotonically increasing +""" +A helper class for generating thread safe monotonically increasing id numbers. +.. note:: + + This code is thread safe but not process safe; for use only + within one python process. """ import itertools @@ -17,11 +22,19 @@ logger = logging.getLogger(__name__) generators = {} -def get(name: str, *, start=0) -> int: +def get(name: str, *, start: int = 0) -> int: """ Returns a thread-safe, monotonically increasing id suitable for use as a globally unique identifier. + Args: + name: the sequence identifier name. + start: the starting id (i.e. the first id that should be returned) + + Returns: + An integer id such that within one sequence identifier name the + id returned is unique and is the maximum id ever returned. + >>> import id_generator >>> id_generator.get('student_id') 0 @@ -35,11 +48,11 @@ def get(name: str, *, start=0) -> int: if name not in generators: generators[name] = itertools.count(start, 1) x = next(generators[name]) - logger.debug("Generated next id %d", x) + logger.debug("Generated next id %d in sequence %s", x, name) return x -if __name__ == '__main__': +if __name__ == "__main__": import doctest doctest.testmod()