Skip to content

Commit 8cf7983

Browse files
committed
get type hints if a forward reference is used
Signed-off-by: Zen <[email protected]>
1 parent 811ed73 commit 8cf7983

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/zenlib/types/validated_dataclass.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from dataclasses import dataclass
2+
from typing import ForwardRef, Union, get_args, get_origin, get_type_hints
23

34

45
def validatedDataclass(cls):
56
from zenlib.logging import loggify
67
from zenlib.util import merge_class
78

8-
99
cls = loggify(dataclass(cls))
1010
base_annotations = {}
1111
for base in cls.__mro__:
@@ -28,6 +28,9 @@ def _validate_attribute(self, attribute, value):
2828
expected_type = self.__class__.__annotations__.get(attribute)
2929
if not expected_type:
3030
return value # No type hint, so we can't validate it
31+
if get_origin(expected_type) is Union and isinstance(get_args(expected_type)[0], ForwardRef):
32+
expected_type = get_type_hints(self.__class__)[attribute]
33+
3134
if not isinstance(value, expected_type):
3235
try:
3336
value = expected_type(value)

0 commit comments

Comments
 (0)