Generate ids with itertools.count

Avoids the critical section with threading.Lock in favor of itertools.count.

`count` objects are threadsafe, and their critical section is implemented in C and provide better performance that Python level locking.
This commit is contained in:
Soof Golan
2024-09-02 14:44:48 +02:00
parent 7c342f7ba2
commit 5c0f5a1613

View File

@@ -3,32 +3,39 @@
# #
# SPDX-License-Identifier: BSD 2-Clause License # SPDX-License-Identifier: BSD 2-Clause License
# #
import collections
import itertools
from threading import Lock _COUNTS = collections.defaultdict(itertools.count)
_ID = itertools.count()
_COUNTS = {}
_COUNTS_MUTEX = Lock()
_ID = 0
_ID_MUTEX = Lock()
def obj_id() -> int: def obj_id() -> int:
global _ID, _ID_MUTEX """
with _ID_MUTEX: Generate a unique id for an object.
_ID += 1
return _ID >>> obj_id()
0
>>> obj_id()
1
>>> obj_id()
2
"""
return next(_ID)
def obj_count(obj) -> int: def obj_count(obj) -> int:
global _COUNTS, COUNTS_MUTEX """Generate a unique id for an object.
name = obj.__class__.__name__
with _COUNTS_MUTEX: >>> obj_count(object())
if name not in _COUNTS: 0
_COUNTS[name] = 0 >>> obj_count(object())
else: 1
_COUNTS[name] += 1 >>> new_type = type('NewType', (object,), {})
return _COUNTS[name] >>> obj_count(new_type())
0
"""
return next(_COUNTS[obj.__class__.__name__])
def exp_smoothing(value: float, prev_value: float, factor: float) -> float: def exp_smoothing(value: float, prev_value: float, factor: float) -> float: