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