Skip to content

Commit

Permalink
Merge pull request #24 from BrianPugh/improved-metaclass-support
Browse files Browse the repository at this point in the history
Improved metaclass support
  • Loading branch information
BrianPugh authored Apr 12, 2023
2 parents 4774cff + ee74b22 commit 3819b31
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
13 changes: 4 additions & 9 deletions autoregistry/_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,14 +202,6 @@ def __new__(
# Manipulate namespace instead of modifying attributes after calling __new__ so
# that hooks like __init_subclass__ have appropriately set registry attributes.
# Each subclass gets its own registry.
try:
Registry # pyright: ignore[reportUnusedExpression]
except NameError:
# Should only happen the very first time that
# Registry is being defined.
namespace["__registry__"] = _Registry(RegistryConfig(**config))
new_cls = super().__new__(cls, cls_name, bases, namespace)
return new_cls

# Copy the nearest parent config, then update it with new params
for parent_cls in bases:
Expand All @@ -219,7 +211,10 @@ def __new__(
except AttributeError:
pass
else:
raise InternalError("Should never happen.") # pragma: no cover
# No parent config, create a new one from scratch.
namespace["__registry__"] = _Registry(RegistryConfig(**config))
new_cls = super().__new__(cls, cls_name, bases, namespace)
return new_cls

# Derive registry name before updating registry config, since a classes own name is
# subject to it's parents configuration, not its own.
Expand Down
26 changes: 26 additions & 0 deletions tests/test_meta_extension.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from autoregistry import RegistryMeta


class ExtendedRegistryMeta(RegistryMeta):
def __call__(cls, *args, **kwargs): # noqa: N805
out = super().__call__(*args, **kwargs)
out.extended_attribute = cls.__name__
return out


class Foo(metaclass=ExtendedRegistryMeta):
pass


class Bar(Foo):
pass


def test_extended_registry():
foo = Foo()
bar = Bar()

assert foo.extended_attribute == "Foo"
assert bar.extended_attribute == "Bar"

assert list(Foo) == ["bar"]

0 comments on commit 3819b31

Please sign in to comment.