$ git clone https://gist.github.com/ivangeorgiev/204c8e0310c2a7eea07970eae824f3a1 class-decorator-example
...
$ cd class-decorator-example
Last active
October 21, 2022 13:49
-
-
Save ivangeorgiev/204c8e0310c2a7eea07970eae824f3a1 to your computer and use it in GitHub Desktop.
Track created class instances in registry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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