@@ -10,8 +10,8 @@ def safe_deepcopy(obj: Any) -> Any:
1010 """
1111 Attempts to create a deep copy of the object using `copy.deepcopy`
1212 whenever possible. If that fails, it falls back to custom deep copy
13- logic or returns the original object .
14-
13+ logic. If that also fails, it raises a `DeepCopyError` .
14+
1515 Args:
1616 obj (Any): The object to be copied, which can be of any type.
1717
@@ -26,13 +26,7 @@ def safe_deepcopy(obj: Any) -> Any:
2626 try :
2727
2828 # Try to use copy.deepcopy first
29- if isinstance (obj ,BaseModel ):
30- # handle BaseModel because __fields_set__ need compatibility
31- copied_obj = obj .copy (deep = True )
32- else :
33- copied_obj = copy .deepcopy (obj )
34-
35- return copied_obj
29+ return copy .deepcopy (obj )
3630 except (TypeError , AttributeError ) as e :
3731 # If deepcopy fails, handle specific types manually
3832
@@ -65,14 +59,17 @@ def safe_deepcopy(obj: Any) -> Any:
6559
6660 # Handle objects with attributes
6761 elif hasattr (obj , "__dict__" ):
68- new_obj = obj .__new__ (obj .__class__ )
69- for attr in obj .__dict__ :
70- setattr (new_obj , attr , safe_deepcopy (getattr (obj , attr )))
71-
72- return new_obj
73-
62+ # If an object cannot be deep copied, then the sub-properties of \
63+ # the object will not be analyzed and shallow copy will be used directly.
64+ try :
65+ return copy .copy (obj )
66+ except (TypeError , AttributeError ):
67+ raise DeepCopyError (f"Cannot deep copy the object of type { type (obj )} " ) from e
68+
69+
7470 # Attempt shallow copy as a fallback
7571 try :
7672 return copy .copy (obj )
7773 except (TypeError , AttributeError ):
7874 raise DeepCopyError (f"Cannot deep copy the object of type { type (obj )} " ) from e
75+
0 commit comments