Skip to content

Commit

Permalink
Don't allow setitem on Registry subclasses
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianPugh committed Oct 24, 2023
1 parent 4e820f1 commit 41f5a73
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
6 changes: 5 additions & 1 deletion autoregistry/_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
InvalidNameError,
KeyCollisionError,
ModuleAliasError,
RegistryError,
)


Expand Down Expand Up @@ -146,7 +147,10 @@ def __getitem__(self, key: str) -> Type:
return self.__registry__.config.getitem(self.__registry__, key)

def __setitem__(self, key: str, value: Any):
self.__registry__.register(value, key, root=True)
if type(self) is RegistryDecorator:
self.__registry__.register(value, key, root=True)
else:
raise RegistryError("Cannot directly setitem on a Registry subclass.")

def __iter__(self) -> Generator[str, None, None]:
yield from self.__registry__
Expand Down
14 changes: 14 additions & 0 deletions tests/test_classes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pytest
from common import construct_pokemon_classes

import autoregistry
from autoregistry import Registry


Expand Down Expand Up @@ -81,6 +82,19 @@ def test_defaults_get():
assert Pokemon.get("foo", Charmander) == Charmander


def test_classes_setitem_exception():
"""Don't allow setting items for a Registry subclass since it breaks the hierarchy."""

class Foo(Registry):
pass

def bar():
pass

with pytest.raises(autoregistry.RegistryError):
Foo["bar"] = bar


def test_multiple_inheritence_last():
class Foo:
pass
Expand Down

0 comments on commit 41f5a73

Please sign in to comment.