@@ -10,8 +10,8 @@ def safe_deepcopy(obj: Any) -> Any:
10
10
"""
11
11
Attempts to create a deep copy of the object using `copy.deepcopy`
12
12
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
+
15
15
Args:
16
16
obj (Any): The object to be copied, which can be of any type.
17
17
@@ -26,13 +26,7 @@ def safe_deepcopy(obj: Any) -> Any:
26
26
try :
27
27
28
28
# 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 )
36
30
except (TypeError , AttributeError ) as e :
37
31
# If deepcopy fails, handle specific types manually
38
32
@@ -65,14 +59,17 @@ def safe_deepcopy(obj: Any) -> Any:
65
59
66
60
# Handle objects with attributes
67
61
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
+
74
70
# Attempt shallow copy as a fallback
75
71
try :
76
72
return copy .copy (obj )
77
73
except (TypeError , AttributeError ):
78
74
raise DeepCopyError (f"Cannot deep copy the object of type { type (obj )} " ) from e
75
+
0 commit comments