-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcopy.py
71 lines (50 loc) · 1.54 KB
/
copy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
copy module
"""
import copy
from typing import Any
class DeepCopyError(Exception):
"""
Custom exception raised when an object cannot be deep-copied.
"""
pass
def is_boto3_client(obj):
"""
Function for understanding if the script is using boto3 or not
"""
import sys
boto3_module = sys.modules.get("boto3")
if boto3_module:
try:
from botocore.client import BaseClient
return isinstance(obj, BaseClient)
except (AttributeError, ImportError):
return False
return False
def safe_deepcopy(obj: Any) -> Any:
"""
Safely create a deep copy of an object, handling special cases.
Args:
obj: Object to copy
Returns:
Deep copy of the object
Raises:
DeepCopyError: If object cannot be deep copied
"""
try:
# Handle special cases first
if obj is None or isinstance(obj, (str, int, float, bool)):
return obj
if isinstance(obj, (list, set)):
return type(obj)(safe_deepcopy(v) for v in obj)
if isinstance(obj, dict):
return {k: safe_deepcopy(v) for k, v in obj.items()}
if isinstance(obj, tuple):
return tuple(safe_deepcopy(v) for v in obj)
if isinstance(obj, frozenset):
return frozenset(safe_deepcopy(v) for v in obj)
if is_boto3_client(obj):
return obj
return copy.copy(obj)
except Exception as e:
raise DeepCopyError(f"Cannot deep copy object of type {type(obj)}") from e