@@ -158,8 +158,12 @@ def _serialize_value(
158158 exclude : set [str ] | None ,
159159 exclude_none : bool ,
160160 attribute_name : str ,
161+ active_container_ids : set [int ] | None = None ,
162+ stringify_dict_keys : bool = False ,
161163) -> Any :
162164 """Recursively serialize a value while preserving skip semantics."""
165+ if active_container_ids is None :
166+ active_container_ids = set ()
163167 if type (value ) in _JSON_SCALAR_TYPES :
164168 return value
165169 if _is_serialization_protocol (value ):
@@ -169,34 +173,54 @@ def _serialize_value(
169173 exclude = exclude ,
170174 exclude_none = exclude_none ,
171175 attribute_name = attribute_name ,
176+ active_container_ids = active_container_ids ,
172177 )
173178 if isinstance (value , list ):
174- serialized_list : list [Any ] = []
175- for item in cast (list [Any ], value ):
176- serialized = _serialize_value (
177- item ,
178- exclude = exclude ,
179- exclude_none = exclude_none ,
180- attribute_name = attribute_name ,
181- )
182- if serialized is not _SKIP_SERIALIZATION :
183- serialized_list .append (serialized )
184- return serialized_list
179+ value_as_list = cast (list [Any ], value )
180+ container_id = id (value_as_list )
181+ if container_id in active_container_ids :
182+ raise ValueError ("Circular reference detected" )
183+ active_container_ids .add (container_id )
184+ try :
185+ serialized_list : list [Any ] = []
186+ for item in value_as_list :
187+ serialized = _serialize_value (
188+ item ,
189+ exclude = exclude ,
190+ exclude_none = exclude_none ,
191+ attribute_name = attribute_name ,
192+ active_container_ids = active_container_ids ,
193+ )
194+ if serialized is not _SKIP_SERIALIZATION :
195+ serialized_list .append (serialized )
196+ return serialized_list
197+ finally :
198+ active_container_ids .remove (container_id )
185199 if isinstance (value , dict ):
186- serialized_dict : dict [str , Any ] = {}
187- for raw_key , item in cast (dict [Any , Any ], value ).items ():
188- if isinstance (item , (datetime , date , time )):
189- serialized_dict [str (raw_key )] = str (item )
190- continue
191- serialized = _serialize_value (
192- item ,
193- exclude = exclude ,
194- exclude_none = exclude_none ,
195- attribute_name = attribute_name ,
196- )
197- if serialized is not _SKIP_SERIALIZATION :
198- serialized_dict [str (raw_key )] = serialized
199- return serialized_dict
200+ value_as_dict = cast (dict [Any , Any ], value )
201+ container_id = id (value_as_dict )
202+ if container_id in active_container_ids :
203+ raise ValueError ("Circular reference detected" )
204+ active_container_ids .add (container_id )
205+ try :
206+ serialized_dict : dict [Any , Any ] = {}
207+ for raw_key , item in value_as_dict .items ():
208+ dict_key = str (raw_key ) if stringify_dict_keys else raw_key
209+ if isinstance (item , (datetime , date , time )):
210+ serialized_dict [dict_key ] = str (item )
211+ continue
212+ serialized = _serialize_value (
213+ item ,
214+ exclude = exclude ,
215+ exclude_none = exclude_none ,
216+ attribute_name = attribute_name ,
217+ active_container_ids = active_container_ids ,
218+ )
219+ if serialized is not _SKIP_SERIALIZATION :
220+ serialized_dict [dict_key ] = serialized
221+ return serialized_dict
222+ finally :
223+ active_container_ids .remove (container_id )
200224 if is_serializable (value ):
201225 return value
202226 logger .debug (f"Skipping non-serializable value in attribute '{ attribute_name } ' of type { type (value ).__name__ } " )
@@ -392,6 +416,7 @@ def to_dict(self, *, exclude: set[str] | None = None, exclude_none: bool = True)
392416 exclude = exclude ,
393417 exclude_none = exclude_none ,
394418 attribute_name = key ,
419+ stringify_dict_keys = isinstance (value , dict ),
395420 )
396421 if serialized is not _SKIP_SERIALIZATION :
397422 result [key ] = serialized
0 commit comments