Skip to content

Instantly share code, notes, and snippets.

@ivangeorgiev
Last active October 21, 2022 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivangeorgiev/204c8e0310c2a7eea07970eae824f3a1 to your computer and use it in GitHub Desktop.
Save ivangeorgiev/204c8e0310c2a7eea07970eae824f3a1 to your computer and use it in GitHub Desktop.
Track created class instances in registry

Class Instance Registry with Python Class Decorator

Getting the source code:

$ git clone https://gist.github.com/ivangeorgiev/204c8e0310c2a7eea07970eae824f3a1 class-decorator-example
...
$ cd class-decorator-example

Running Tests

# You need pytest
$ pip insall pytest
$ pytest
...
"""Python class decorator to track created instances in registry
Example usage:
orders = []
@registered(orders)
class Order:
...
order1 = Order()
assert order1 in orders
"""
def registered(registry):
def decorator(cls):
def cls_factory(*args, **kwargs):
instance = cls(*args, **kwargs)
registry.append(instance)
return instance
return cls_factory
return decorator
"""Pytest unit tests for `registered` class decorator"""
import pytest
from registered import registered
class FakeClass:
pass
class TestRegisteredDecorator:
@pytest.fixture(name="registry")
def given_registry(self):
return []
@pytest.fixture(name="decorated")
def given_decorated(self, registry):
return registered(registry)(FakeClass)
def test_given_decorated_class_when_create_instance_then_instance_is_in_registry(
self, registry, decorated
):
instance = decorated()
assert isinstance(instance, FakeClass)
assert instance in registry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment