dc2ac9cc810a4e1d588d60231371e873d9d31966
[python_utils.git] / id_generator.py
1 #!/usr/bin/env python3
2
3 """A helper class for generating thread safe monotonically increasing
4 id numbers."""
5
6 import itertools
7 import logging
8
9 # This module is commonly used by others in here and should avoid
10 # taking any unnecessary dependencies back on them.
11
12 logger = logging.getLogger(__name__)
13 generators = {}
14
15
16 def get(name: str, *, start=0) -> int:
17     """
18     Returns a thread safe monotonically increasing id suitable for use
19     as a globally unique identifier.
20
21     >>> import id_generator
22     >>> id_generator.get('student_id')
23     0
24     >>> id_generator.get('student_id')
25     1
26     >>> id_generator.get('employee_id', start=10000)
27     10000
28     >>> id_generator.get('employee_id', start=10000)
29     10001
30     """
31     if name not in generators:
32         generators[name] = itertools.count(start, 1)
33     x = next(generators[name])
34     logger.debug("Generated next id %d", x)
35     return x
36
37
38 if __name__ == '__main__':
39     import doctest
40
41     doctest.testmod()