I need to keep track of groups of objects, which I want to access from anywhere in my code.
this is my 5 minute solution:
# this is in the __init__.py of the main directory of the package.
# I import just the functions in all the other modules where i need to access the groups
_groups = {}
def add_to_group(group_name: str, thing) -> None:
if group_name in _groups.keys():
_groups[group_name].append(thing)
else:
_groups[group_name] = [thing]
def remove_from_group(group_name: str, thing) -> None:
if group_name in _groups.keys():
ix = _groups[group_name].index(thing)
_groups[group_name].pop(ix)
else:
raise NameError(f"group_name '{group_name}' was not found in groups. group names found were {_groups.keys()}")
def get_all_in_group(group_name: str) -> list:
return _groups.get(group_name, [])
def delete_group(group_name: str) -> list:
return _groups.pop(group_name)
if __name__ == "__main__":
my_thing = 5
add_to_group("stuff", my_thing)
add_to_group("more_stuff", my_thing)
print(get_all_in_group("stuff"))
remove_from_group("stuff", my_thing)
print(get_all_in_group("stuff"))
delete_group("stuff")
print(_groups)
remove_from_group("stuff", my_thing)
I’m wondering:
-
do yall ever do this?
-
does something like this already exist, or maybe there is a more ‘pythonic’ way of doing it? (i know about global vars, just trying to avoid them)
-
are there any obvious downsides or pitfalls to this approach?
I’m aware of the errors that would be caused by passing group names that don’t exist
also aware that things could get funky placing duplicate or equivalent objects in the same group. in my use case everything should be unique.
2
Providing that all objects you put into groups are hashable and that order of insertion doesn’t matter you can simply use a defaultdict
of sets instead for the purpose.
Your sample code can then become:
from collections import defaultdict
groups = defaultdict(set)
my_thing = 5
groups["stuff"].add(my_thing)
groups["more_stuff"].add(my_thing)
print(groups["stuff"])
groups["stuff"].remove(my_thing)
print(groups["stuff"])
del groups["stuff"]
print(groups)
groups["stuff"].remove(my_thing)
If some of the objects are unhashable or if the order of insertion is important, you can use a defaultdict
of lists instead, in which case you would use list.append
to add an object and list.remove
to remove one.
2