Skip to content

Commit cd21b36

Browse files
pasmudCommandCodeBotagronholm
authored
Fixed TypedAttributeSet not collecting annotations from superclasses (#1358)
Co-authored-by: pasmud <[email protected]> Co-authored-by: CommandCodeBot <[email protected]> Co-authored-by: Alex Grönholm <[email protected]>
1 parent b7f8c68 commit cd21b36

3 files changed

Lines changed: 22 additions & 2 deletions

File tree

‎changelog.d/1358.fixed.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed ``TypeError`` when subclassing an existing ``TypedAttributeSet``
2+
subclass, and this subclass contains type annotations

‎src/anyio/_core/_typedattr.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,12 @@ class TypedAttributeSet:
2727
"""
2828

2929
def __init_subclass__(cls) -> None:
30-
annotations: dict[str, Any] = getattr(cls, "__annotations__", {})
30+
# Collect the annotations from the whole MRO, as __annotations__ only ever
31+
# contains the ones declared in the class itself
32+
annotations: set[str] = set()
33+
for class_ in cls.__mro__:
34+
annotations.update(getattr(class_, "__annotations__", {}))
35+
3136
for attrname in dir(cls):
3237
if not attrname.startswith("_") and attrname not in annotations:
3338
raise TypeError(

‎tests/test_typedattr.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import pytest
77

8-
from anyio import TypedAttributeProvider
8+
from anyio import TypedAttributeProvider, TypedAttributeSet, typed_attribute
99

1010

1111
class DummyAttributeProvider(TypedAttributeProvider):
@@ -25,3 +25,16 @@ def test_typedattr_keyerror() -> None:
2525
"""
2626
with pytest.raises(KeyError, match="^'foo'$"):
2727
DummyAttributeProvider().extra(str)
28+
29+
30+
def test_typedattr_set_subclassing() -> None:
31+
"""
32+
Test that an attribute set can be subclassed, and that the attributes inherited
33+
from the base set are not reported as missing annotations.
34+
"""
35+
36+
class BaseAttributeSet(TypedAttributeSet):
37+
attr1: int = typed_attribute()
38+
39+
class DerivedAttributeSet(BaseAttributeSet):
40+
attr2: str = typed_attribute()

0 commit comments

Comments
 (0)