This project provides a simple utility for collecting all instances of your Python classes. It offers easy integration into your projects with a decorator.
Note: All instances of your classes decorated using InstanceCollector are stored in RAM until the program exits. Use this utility wisely to avoid memory leaks.
- Collecting instances using a decorator.
- Capability to iterate over instances of a class with optional filtering.
You can install the package using poetry:
poetry add git+https://github.com/ulbwa/instance-collector- Import InstanceCollector:
from instance_collector import *- Decorate your class with
@InstanceCollector.collect:
@InstanceCollector.collect
class MyClass:
def __init__(self, value: str):
self.value = value
def __repr__(self) -> str:
return f'MyClass({self.value!r})'- Create instances of your class:
obj1 = MyClass(value="First instance")
obj2 = MyClass(value="Second instance")
obj3 = MyClass(value="Third instance")- Access the instances through the collector:
for obj in InstanceCollector.iter(MyClass):
print(obj)- Iterate over instances with filtering:
filter_fn = lambda x: "Second" in x.value
print(list(InstanceCollector.iter(MyClass, filter_fn)))Special thx to doil45 for providing the excellent Python penetration experience.