Coverage for tinytroupe / utils / misc.py: 41%
27 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-28 17:48 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-28 17:48 +0000
1import hashlib
2import os
3import sys
4from typing import Union
7################################################################################
8# Other
9################################################################################
10AgentOrWorld = Union["TinyPerson", "TinyWorld"]
12def first_non_none(*args):
13 """
14 Returns the first non-None argument from the provided arguments.
16 Args:
17 *args: Variable length argument list.
19 Returns:
20 The first non-None argument, or None if all are None.
21 """
22 for arg in args:
23 if arg is not None:
24 return arg
25 return None
27def name_or_empty(named_entity: AgentOrWorld):
28 """
29 Returns the name of the specified agent or environment, or an empty string if the agent is None.
30 """
31 if named_entity is None:
32 return ""
33 else:
34 return named_entity.name
36def custom_hash(obj):
37 """
38 Returns a hash for the specified object. The object is first converted
39 to a string, to make it hashable. This method is deterministic,
40 contrary to the built-in hash() function.
41 """
43 return hashlib.sha256(str(obj).encode()).hexdigest()
45# Replace the global counter with a dictionary of counters per scope
46_fresh_id_counters = {"default": 0}
48def fresh_id(scope="default"):
49 """
50 Returns a fresh ID for a new object within the specified scope.
51 Different scopes have independent ID sequences.
53 Args:
54 scope (str): The scope to generate the ID in. Defaults to "default".
56 Returns:
57 int: A unique ID within the specified scope.
58 """
59 global _fresh_id_counters
61 # Initialize the counter for this scope if it doesn't exist
62 if scope not in _fresh_id_counters:
63 _fresh_id_counters[scope] = 0
65 _fresh_id_counters[scope] += 1
66 return _fresh_id_counters[scope]
68def reset_fresh_id(scope=None):
69 """
70 Resets the fresh ID counter for the specified scope or for all scopes.
72 Args:
73 scope (str, optional): The scope to reset. If None, resets all scopes.
74 """
75 global _fresh_id_counters
77 if scope is None:
78 # Reset all counters
79 _fresh_id_counters = {"default": 0}
80 elif scope in _fresh_id_counters:
81 # Reset only the specified scope
82 _fresh_id_counters[scope] = 0