1- """
2- copy module
3- """
41import copy
5- from typing import Any , Dict , Optional
6- from pydantic . v1 import BaseModel
2+ from typing import Any
3+
74
85class DeepCopyError (Exception ):
9- """Custom exception raised when an object cannot be deep-copied."""
6+ """
7+ Custom exception raised when an object cannot be deep-copied.
8+ """
9+
1010 pass
1111
12+
13+ def is_boto3_client (obj ):
14+ """
15+ Function for understanding if the script is using boto3 or not
16+ """
17+ import sys
18+
19+ boto3_module = sys .modules .get ("boto3" )
20+
21+ if boto3_module :
22+ try :
23+ from botocore .client import BaseClient
24+
25+ return isinstance (obj , BaseClient )
26+ except (AttributeError , ImportError ):
27+ return False
28+ return False
29+
30+
1231def safe_deepcopy (obj : Any ) -> Any :
1332 """
1433 Attempts to create a deep copy of the object using `copy.deepcopy`
1534 whenever possible. If that fails, it falls back to custom deep copy
1635 logic. If that also fails, it raises a `DeepCopyError`.
17-
36+
1837 Args:
1938 obj (Any): The object to be copied, which can be of any type.
2039
@@ -27,36 +46,40 @@ def safe_deepcopy(obj: Any) -> Any:
2746 """
2847
2948 try :
49+
3050 return copy .deepcopy (obj )
3151 except (TypeError , AttributeError ) as e :
52+
3253 if isinstance (obj , dict ):
3354 new_obj = {}
55+
3456 for k , v in obj .items ():
3557 new_obj [k ] = safe_deepcopy (v )
3658 return new_obj
3759
3860 elif isinstance (obj , list ):
3961 new_obj = []
62+
4063 for v in obj :
4164 new_obj .append (safe_deepcopy (v ))
4265 return new_obj
4366
4467 elif isinstance (obj , tuple ):
4568 new_obj = tuple (safe_deepcopy (v ) for v in obj )
69+
4670 return new_obj
4771
4872 elif isinstance (obj , frozenset ):
4973 new_obj = frozenset (safe_deepcopy (v ) for v in obj )
5074 return new_obj
5175
52- elif hasattr (obj , "__dict__" ):
76+ elif is_boto3_client (obj ):
77+ return obj
78+
79+ else :
5380 try :
5481 return copy .copy (obj )
5582 except (TypeError , AttributeError ):
56- raise DeepCopyError (f"Cannot deep copy the object of type { type (obj )} " ) from e
57-
58-
59- try :
60- return copy .copy (obj )
61- except (TypeError , AttributeError ):
62- raise DeepCopyError (f"Cannot deep copy the object of type { type (obj )} " ) from e
83+ raise DeepCopyError (
84+ f"Cannot deep copy the object of type { type (obj )} "
85+ ) from e
0 commit comments