@@ -149,6 +149,22 @@ def default(obj: Any) -> Any:
149149 raise TypeError (f"Serialization of { type (obj )} is not supported." )
150150
151151
152+ def __save (obj ):
153+ """Calls the legacy save method to save the object to temp json
154+ then load it into a dictionary.
155+ """
156+ try :
157+ temp_file = tempfile .NamedTemporaryFile (
158+ mode = "w" , encoding = "utf-8" , suffix = ".json" , delete = False
159+ )
160+ temp_file .close ()
161+ obj .save (temp_file .name )
162+ with open (temp_file .name , "r" , encoding = "utf-8" ) as f :
163+ return json .load (f )
164+ finally :
165+ os .unlink (temp_file .name )
166+
167+
152168def dump (obj : Any ) -> Dict [str , Any ]:
153169 """Return a json dict representation of an object.
154170
@@ -167,14 +183,14 @@ def dump(obj: Any) -> Dict[str, Any]:
167183 ):
168184 # The object is not is_lc_serializable.
169185 # However, it supports the legacy save() method.
170- try :
171- temp_file = tempfile . NamedTemporaryFile (
172- mode = "w" , encoding = "utf-8" , suffix = ".json" , delete = False
173- )
174- temp_file . close ()
175- obj . save ( temp_file . name )
176- with open ( temp_file . name , "r" , encoding = "utf-8" ) as f :
177- return json . load ( f )
178- finally :
179- os . unlink ( temp_file . name )
180- return json . loads ( json . dumps ( obj , default = default ))
186+ return __save ( obj )
187+ # The object is is_lc_serializable.
188+ # However, some properties may not be serializable
189+ # Here we try to dump the object and fallback to the save() method
190+ # if there is an error.
191+ try :
192+ return json . loads ( json . dumps ( obj , default = default ))
193+ except TypeError as ex :
194+ if isinstance ( obj , Serializable ) and hasattr ( obj , "save" ) :
195+ return __save ( obj )
196+ raise ex
0 commit comments