|
| 1 | +import copy |
1 | 2 | import os |
2 | 3 | import types |
3 | 4 | from collections.abc import MutableSequence |
4 | 5 | from functools import total_ordering |
| 6 | +from typing import Any |
5 | 7 |
|
6 | 8 | __version__ = "1.8.1.dev0" |
7 | 9 |
|
8 | | -__all__ = ("FrozenList", "PyFrozenList") # type: Tuple[str, ...] |
| 10 | +__all__ = ( |
| 11 | + "FrozenList", |
| 12 | + "PyFrozenList", |
| 13 | + "_reconstruct_pyfrozenlist", |
| 14 | +) # type: Tuple[str, ...] |
9 | 15 |
|
10 | 16 |
|
11 | 17 | NO_EXTENSIONS = bool(os.environ.get("FROZENLIST_NO_EXTENSIONS")) # type: bool |
@@ -73,7 +79,43 @@ def __hash__(self): |
73 | 79 | else: |
74 | 80 | raise RuntimeError("Cannot hash unfrozen list.") |
75 | 81 |
|
| 82 | + def __deepcopy__(self, memo: dict[int, Any]): |
| 83 | + obj_id = id(self) |
76 | 84 |
|
| 85 | + # Return existing copy if already processed (circular reference) |
| 86 | + if obj_id in memo: |
| 87 | + return memo[obj_id] |
| 88 | + |
| 89 | + # Create new instance and register immediately |
| 90 | + new_list = self.__class__([]) |
| 91 | + memo[obj_id] = new_list |
| 92 | + |
| 93 | + # Deep copy items |
| 94 | + new_list._items[:] = [copy.deepcopy(item, memo) for item in self._items] |
| 95 | + |
| 96 | + # Preserve frozen state |
| 97 | + if self._frozen: |
| 98 | + new_list.freeze() |
| 99 | + |
| 100 | + return new_list |
| 101 | + |
| 102 | + def __reduce__(self): |
| 103 | + return ( |
| 104 | + _reconstruct_pyfrozenlist, |
| 105 | + (self._items, self._frozen), |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +def _reconstruct_pyfrozenlist(items, frozen): |
| 110 | + """Helper function to reconstruct the pure Python FrozenList during unpickling. |
| 111 | + This function is needed since otherwise the class renaming confuses pickle.""" |
| 112 | + fl = PyFrozenList(items) |
| 113 | + if frozen: |
| 114 | + fl.freeze() |
| 115 | + return fl |
| 116 | + |
| 117 | + |
| 118 | +# Store a reference to the pure Python implementation before it's potentially replaced |
77 | 119 | PyFrozenList = FrozenList |
78 | 120 |
|
79 | 121 |
|
|
0 commit comments