Cut version 0.0.1b4
[pyutils.git] / src / pyutils / id_generator.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """
6 A helper class for generating thread safe monotonically increasing
7 id numbers.
8 """
9
10 import itertools
11 import logging
12
13 # This module is commonly used by others in here and should avoid
14 # taking any unnecessary dependencies back on them.
15
16 logger = logging.getLogger(__name__)
17 generators = {}
18
19
20 def get(name: str, *, start=0) -> int:
21     """
22     Returns a thread-safe, monotonically increasing id suitable for use
23     as a globally unique identifier.
24
25     Args:
26         name: the sequence identifier name.
27         start: the starting id (i.e. the first id that should be returned)
28
29     Returns:
30         An integer id such that within one sequence identifier name the
31         id returned is unique and is the maximum id ever returned.
32
33     >>> import id_generator
34     >>> id_generator.get('student_id')
35     0
36     >>> id_generator.get('student_id')
37     1
38     >>> id_generator.get('employee_id', start=10000)
39     10000
40     >>> id_generator.get('employee_id', start=10000)
41     10001
42     """
43     if name not in generators:
44         generators[name] = itertools.count(start, 1)
45     x = next(generators[name])
46     logger.debug("Generated next id %d in sequence %s", x, name)
47     return x
48
49
50 if __name__ == '__main__':
51     import doctest
52
53     doctest.testmod()