@@ -63,6 +63,16 @@ def _is_type_kind_convertible_to(src_type_kind: str, dst_type_kind: str) -> bool
6363 )
6464
6565
66+ def _get_cached_type_info (
67+ type_to_analyze : Any ,
68+ cache : dict [Any , AnalyzedTypeInfo ],
69+ ) -> AnalyzedTypeInfo :
70+ """Retrieve or compute and cache the type information for a given type."""
71+ if type_to_analyze not in cache :
72+ cache [type_to_analyze ] = analyze_type_info (type_to_analyze )
73+ return cache [type_to_analyze ]
74+
75+
6676def _encode_engine_value_core (
6777 value : Any ,
6878 type_hint : Type [Any ] | str | None = None ,
@@ -104,11 +114,9 @@ def _encode_engine_value_core(
104114 and isinstance (type_variant .variant , AnalyzedListType )
105115 and type_variant .variant .elem_type
106116 ):
107- # Cache the analyzed element type
108- elem_type = type_variant .variant .elem_type
109- if elem_type not in _elem_type_cache :
110- _elem_type_cache [elem_type ] = analyze_type_info (elem_type )
111- elem_type_info = _elem_type_cache [elem_type ]
117+ elem_type_info = _get_cached_type_info (
118+ type_variant .variant .elem_type , _elem_type_cache
119+ )
112120 return [
113121 _encode_engine_value_core (
114122 v ,
@@ -127,7 +135,9 @@ def _encode_engine_value_core(
127135 if type_variant and isinstance (type_variant .variant , AnalyzedBasicType ):
128136 is_json_type = type_variant .variant .kind == "Json"
129137 elif type_hint :
130- hint_type_info = type_variant or analyze_type_info (type_hint )
138+ hint_type_info = type_variant or _get_cached_type_info (
139+ type_hint , _elem_type_cache
140+ )
131141 is_json_type = (
132142 isinstance (hint_type_info .variant , AnalyzedBasicType )
133143 and hint_type_info .variant .kind == "Json"
@@ -151,11 +161,9 @@ def _encode_engine_value_core(
151161 and isinstance (type_variant .variant , AnalyzedDictType )
152162 and type_variant .variant .value_type
153163 ):
154- # Cache the analyzed value type
155- value_type = type_variant .variant .value_type
156- if value_type not in _elem_type_cache :
157- _elem_type_cache [value_type ] = analyze_type_info (value_type )
158- value_type_info = _elem_type_cache [value_type ]
164+ value_type_info = _get_cached_type_info (
165+ type_variant .variant .value_type , _elem_type_cache
166+ )
159167 return {
160168 k : _encode_engine_value_core (
161169 v ,
@@ -184,7 +192,7 @@ def encode_engine_value(value: Any, type_hint: Type[Any] | str | None = None) ->
184192 return _encode_engine_value_core (value )
185193
186194 # Analyze type once and reuse the result
187- type_info = analyze_type_info (type_hint )
195+ type_info = _get_cached_type_info (type_hint , {} )
188196 if isinstance (type_info .variant , AnalyzedUnknownType ):
189197 raise ValueError (f"Type annotation `{ type_info .core_type } ` is unsupported" )
190198
0 commit comments