Skip to content

Commit b94ba17

Browse files
committed
copy annotations from base classes and use __annotations__
this is much faster than get_type_hints Signed-off-by: Zen <[email protected]>
1 parent 41b88ad commit b94ba17

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/zenlib/types/validated_dataclass.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
from dataclasses import dataclass
2-
from typing import get_type_hints
32

43

54
def validatedDataclass(cls):
65
from zenlib.logging import loggify
76
from zenlib.util import merge_class
87

8+
99
cls = loggify(dataclass(cls))
10+
base_annotations = {}
11+
for base in cls.__mro__:
12+
base_annotations.update(getattr(base, "__annotations__", {}))
13+
14+
cls.__annotations__.update(base_annotations)
1015

1116
class ValidatedDataclass(cls):
1217
def __setattr__(self, attribute, value):
@@ -20,7 +25,9 @@ def _validate_attribute(self, attribute, value):
2025
if value is None:
2126
return
2227

23-
expected_type = get_type_hints(self.__class__)[attribute]
28+
expected_type = self.__class__.__annotations__.get(attribute)
29+
if not expected_type:
30+
return value # No type hint, so we can't validate it
2431
if not isinstance(value, expected_type):
2532
try:
2633
value = expected_type(value)

0 commit comments

Comments
 (0)