Merge pull request #437 from soof-golan/soof-obj-id-generation

Generate ids with itertools.count
This commit is contained in:
Aleix Conchillo Flaqué
2024-09-02 10:53:48 -07:00
committed by GitHub

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: