Skip to content

Commit

Permalink
Merge pull request #16 from desultory/dev
Browse files Browse the repository at this point in the history
Get type hints when a forward reference is used
  • Loading branch information
desultory authored Jan 1, 2025
2 parents bd9ee5e + e4c792d commit 308025b
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "zenlib"
version = "3.1.4"
version = "3.1.5"
authors = [
{ name="Desultory", email="[email protected]" },
]
Expand Down
5 changes: 4 additions & 1 deletion src/zenlib/types/validated_dataclass.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from dataclasses import dataclass
from typing import ForwardRef, Union, get_args, get_origin, get_type_hints


def validatedDataclass(cls):
from zenlib.logging import loggify
from zenlib.util import merge_class


cls = loggify(dataclass(cls))
base_annotations = {}
for base in cls.__mro__:
Expand All @@ -28,6 +28,9 @@ def _validate_attribute(self, attribute, value):
expected_type = self.__class__.__annotations__.get(attribute)
if not expected_type:
return value # No type hint, so we can't validate it
if get_origin(expected_type) is Union and isinstance(get_args(expected_type)[0], ForwardRef):
expected_type = get_type_hints(self.__class__)[attribute]

if not isinstance(value, expected_type):
try:
value = expected_type(value)
Expand Down

0 comments on commit 308025b

Please sign in to comment.