Skip to content

Commit d11e720

Browse files
authored
Fix annotated refs when using future annotations for plain classes (#10)
1 parent cf07b83 commit d11e720

4 files changed

Lines changed: 32 additions & 1 deletion

File tree

src/py_avro_schema/_schemas.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1156,8 +1156,13 @@ def __init__(self, py_type: Type, namespace: Optional[str] = None, options: Opti
11561156
super().__init__(py_type, namespace=namespace, options=options)
11571157
py_type = _type_from_annotated(py_type)
11581158

1159+
# Try to get resolved type hints, but fall back to raw annotations if there are unresolved forward refs
1160+
try:
1161+
type_hints = get_type_hints(py_type, include_extras=True)
1162+
except NameError:
1163+
type_hints = py_type.__annotations__
11591164
self.py_fields: list[tuple[str, type]] = []
1160-
for k, v in py_type.__annotations__.items():
1165+
for k, v in type_hints.items():
11611166
self.py_fields.append((k, v))
11621167
# We store __init__ parameters with default values. They can be used as defaults for the record.
11631168
self.signature_fields = {

tests/models/__init__.py

Whitespace-only changes.

tests/models/forward.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from __future__ import annotations
2+
3+
Name = str
4+
5+
6+
class PyClass:
7+
"""For testing imports with future annotations"""
8+
9+
name: Name

tests/test_plain_class.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,3 +143,20 @@ class PyType:
143143

144144
expected = {"fields": [{"name": "details", "type": "string"}], "name": "PyType", "type": "record"}
145145
assert_schema(PyType, expected)
146+
147+
148+
def test_type_aliases():
149+
Name = str
150+
151+
class PyClass:
152+
name: Name
153+
154+
expected = {"fields": [{"name": "name", "type": "string"}], "name": "PyClass", "type": "record"}
155+
assert_schema(PyClass, expected)
156+
157+
158+
def test_type_aliases_future():
159+
from tests.models.forward import PyClass
160+
161+
expected = {"fields": [{"name": "name", "type": "string"}], "name": "PyClass", "type": "record"}
162+
assert_schema(PyClass, expected)

0 commit comments

Comments
 (0)