Skip to content

Commit

Permalink
fix config-passing issues with attrs library.
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianPugh committed Sep 21, 2023
1 parent 4a67602 commit 8174d3a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 11 deletions.
28 changes: 17 additions & 11 deletions autoregistry/_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,18 +203,24 @@ def __new__(
# that hooks like __init_subclass__ have appropriately set registry attributes.
# Each subclass gets its own registry.

# Copy the nearest parent config, then update it with new params
for parent_cls in bases:
try:
registry_config = parent_cls.__registry__.config.copy()
break
except AttributeError:
pass
# Copy the nearest parent config, then update it with new params.
# Some class construction libraries, like ``attrs``, will recreate a class.
# In these situations, the old-class will have it's attributes (like the __registry__
# object) passed in via the ``namespace``.
if "__registry__" in namespace:
registry_config = namespace["__registry__"].config
else:
# 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
for parent_cls in bases:
try:
registry_config = parent_cls.__registry__.config.copy()
break
except AttributeError:
pass
else:
# 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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pytest-cov = ">=3,<5"
pytest-mock = "^3.7.0"
pyright = "^1.1.273"
pytest-pyright = "^0.0.3"
attrs = "^23.1.0"

[tool.coverage.run]
branch = true
Expand Down
20 changes: 20 additions & 0 deletions tests/test_attrs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from attrs import frozen

from autoregistry import Registry


def test_attrs_compatability():
@frozen
class Media(Registry, snake_case=True):
name: str
year: int

class Movie(Media):
pass

class MusicVideo(Media):
pass

assert list(Media) == ["movie", "music_video"]
assert Media["movie"] == Movie
assert Media["music_video"] == MusicVideo

0 comments on commit 8174d3a

Please sign in to comment.