|
| 1 | +import copy |
| 2 | +from typing import Any, Dict, Optional |
| 3 | +from pydantic.v1 import BaseModel |
| 4 | + |
| 5 | +class DeepCopyError(Exception): |
| 6 | + """Custom exception raised when an object cannot be deep-copied.""" |
| 7 | + pass |
| 8 | + |
| 9 | +def safe_deepcopy(obj: Any) -> Any: |
| 10 | + """ |
| 11 | + Attempts to create a deep copy of the object using `copy.deepcopy` |
| 12 | + whenever possible. If that fails, it falls back to custom deep copy |
| 13 | + logic. If that also fails, it raises a `DeepCopyError`. |
| 14 | + |
| 15 | + Args: |
| 16 | + obj (Any): The object to be copied, which can be of any type. |
| 17 | +
|
| 18 | + Returns: |
| 19 | + Any: A deep copy of the object if possible; otherwise, a shallow |
| 20 | + copy if deep copying fails; if neither is possible, the original |
| 21 | + object is returned. |
| 22 | + Raises: |
| 23 | + DeepCopyError: If the object cannot be deep-copied or shallow-copied. |
| 24 | + """ |
| 25 | + |
| 26 | + try: |
| 27 | + |
| 28 | + # Try to use copy.deepcopy first |
| 29 | + return copy.deepcopy(obj) |
| 30 | + except (TypeError, AttributeError) as e: |
| 31 | + # If deepcopy fails, handle specific types manually |
| 32 | + |
| 33 | + # Handle dictionaries |
| 34 | + if isinstance(obj, dict): |
| 35 | + new_obj = {} |
| 36 | + |
| 37 | + for k, v in obj.items(): |
| 38 | + new_obj[k] = safe_deepcopy(v) |
| 39 | + return new_obj |
| 40 | + |
| 41 | + # Handle lists |
| 42 | + elif isinstance(obj, list): |
| 43 | + new_obj = [] |
| 44 | + |
| 45 | + for v in obj: |
| 46 | + new_obj.append(safe_deepcopy(v)) |
| 47 | + return new_obj |
| 48 | + |
| 49 | + # Handle tuples (immutable, but might contain mutable objects) |
| 50 | + elif isinstance(obj, tuple): |
| 51 | + new_obj = tuple(safe_deepcopy(v) for v in obj) |
| 52 | + |
| 53 | + return new_obj |
| 54 | + |
| 55 | + # Handle frozensets (immutable, but might contain mutable objects) |
| 56 | + elif isinstance(obj, frozenset): |
| 57 | + new_obj = frozenset(safe_deepcopy(v) for v in obj) |
| 58 | + return new_obj |
| 59 | + |
| 60 | + # Handle objects with attributes |
| 61 | + elif hasattr(obj, "__dict__"): |
| 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 | + |
| 70 | + # Attempt shallow copy as a fallback |
| 71 | + try: |
| 72 | + return copy.copy(obj) |
| 73 | + except (TypeError, AttributeError): |
| 74 | + raise DeepCopyError(f"Cannot deep copy the object of type {type(obj)}") from e |
| 75 | + |
0 commit comments