global-ish object groups in python

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># 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)
</code>
<code># 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) </code>
# 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:

  1. do yall ever do this?

  2. 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)

  3. 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật