1515from attrs import has as attrs_has
1616from typing_extensions import Self
1717
18+ try :
19+ from annotationlib import ForwardRef as AnnotationForwardRef
20+ except ImportError :
21+ AnnotationForwardRef = None
22+
1823from ._compat import (
1924 ANIES ,
2025 FrozenSetSubscriptable ,
@@ -897,6 +902,8 @@ def _structure_dict(self, obj: Mapping[T, V], cl: Any) -> dict[T, V]:
897902 def _structure_optional (self , obj , union ):
898903 if obj is None :
899904 return None
905+ if AnnotationForwardRef is not None and isinstance (union , AnnotationForwardRef ):
906+ union = union .evaluate ()
900907 union_params = union .__args__
901908 other = union_params [0 ] if union_params [1 ] is NoneType else union_params [1 ]
902909 # We can't actually have a Union of a Union, so this is safe.
@@ -1171,6 +1178,11 @@ def __init__(
11711178 is_frozenset ,
11721179 lambda cl : self .gen_unstructure_iterable (cl , unstructure_to = frozenset ),
11731180 )
1181+ if AnnotationForwardRef is not None :
1182+ self .register_unstructure_hook_factory (
1183+ lambda t : isinstance (t , AnnotationForwardRef ),
1184+ lambda t : self .get_unstructure_hook (t .evaluate ()),
1185+ )
11741186 self .register_unstructure_hook_factory (
11751187 is_optional , self .gen_unstructure_optional
11761188 )
@@ -1189,6 +1201,11 @@ def __init__(
11891201 is_defaultdict , defaultdict_structure_factory
11901202 )
11911203 self .register_structure_hook_factory (is_typeddict , self .gen_structure_typeddict )
1204+ if AnnotationForwardRef is not None :
1205+ self .register_structure_hook_factory (
1206+ lambda t : isinstance (t , AnnotationForwardRef ),
1207+ lambda t : self .get_structure_hook (t .evaluate ()),
1208+ )
11921209 self .register_structure_hook_factory (
11931210 lambda t : get_newtype_base (t ) is not None , self .get_structure_newtype
11941211 )
0 commit comments