@@ -63,6 +63,16 @@ def _is_type_kind_convertible_to(src_type_kind: str, dst_type_kind: str) -> bool
63
63
)
64
64
65
65
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
+
66
76
def _encode_engine_value_core (
67
77
value : Any ,
68
78
type_hint : Type [Any ] | str | None = None ,
@@ -104,11 +114,9 @@ def _encode_engine_value_core(
104
114
and isinstance (type_variant .variant , AnalyzedListType )
105
115
and type_variant .variant .elem_type
106
116
):
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
+ )
112
120
return [
113
121
_encode_engine_value_core (
114
122
v ,
@@ -127,7 +135,9 @@ def _encode_engine_value_core(
127
135
if type_variant and isinstance (type_variant .variant , AnalyzedBasicType ):
128
136
is_json_type = type_variant .variant .kind == "Json"
129
137
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
+ )
131
141
is_json_type = (
132
142
isinstance (hint_type_info .variant , AnalyzedBasicType )
133
143
and hint_type_info .variant .kind == "Json"
@@ -151,11 +161,9 @@ def _encode_engine_value_core(
151
161
and isinstance (type_variant .variant , AnalyzedDictType )
152
162
and type_variant .variant .value_type
153
163
):
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
+ )
159
167
return {
160
168
k : _encode_engine_value_core (
161
169
v ,
@@ -184,7 +192,7 @@ def encode_engine_value(value: Any, type_hint: Type[Any] | str | None = None) ->
184
192
return _encode_engine_value_core (value )
185
193
186
194
# Analyze type once and reuse the result
187
- type_info = analyze_type_info (type_hint )
195
+ type_info = _get_cached_type_info (type_hint , {} )
188
196
if isinstance (type_info .variant , AnalyzedUnknownType ):
189
197
raise ValueError (f"Type annotation `{ type_info .core_type } ` is unsupported" )
190
198
0 commit comments