Skip to content

Commit 863bbb6

Browse files
Fix deepcopy
1 parent 422af6c commit 863bbb6

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/geophires_x_client/geophires_input_parameters.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,12 +145,27 @@ def __hash__(self) -> int:
145145

146146
return hash((param_hash, file_content_hash))
147147

148+
def __deepcopy__(self, memo):
149+
"""
150+
Return the instance itself for deepcopy, as the object is immutable.
151+
152+
This implementation prevents a TypeError when `copy.deepcopy` is used
153+
on an object containing an instance of this class, as it avoids trying
154+
to pickle the internal `mappingproxy` object.
155+
156+
Args:
157+
memo: The memoization dictionary used by `copy.deepcopy` to prevent
158+
infinite recursion in case of circular references.
159+
"""
160+
# Add self to the memoization dictionary to handle circular references correctly.
161+
memo[id(self)] = self
162+
return self
163+
148164
def as_file_path(self) -> Path:
149165
"""
150166
Creates a temporary file representation of the parameters on demand.
151167
The resulting file path is cached on the instance for efficiency.
152168
"""
153-
154169
# Use hasattr to check for the cached attribute on the frozen instance
155170
if hasattr(self, '_cached_file_path'):
156171
return self._cached_file_path

tests/geophires_x_client_tests/test_geophires_input_parameters.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import copy
12
import tempfile
23
import uuid
34
from pathlib import Path
@@ -116,3 +117,16 @@ def test_combining_file_and_params_with_no_trailing_newline(self):
116117

117118
# Clean up the temporary file
118119
base_file_path.unlink()
120+
121+
def test_deepcopy(self):
122+
"""Verify that copy.deepcopy works on an instance without raising a TypeError."""
123+
p1 = ImmutableGeophiresInputParameters(params={'Reservoir Depth': 3})
124+
p2 = None
125+
126+
try:
127+
p2 = copy.deepcopy(p1)
128+
except TypeError:
129+
self.fail('copy.deepcopy(ImmutableGeophiresInputParameters) raised TypeError unexpectedly!')
130+
131+
# For an immutable object, deepcopy should ideally return the same instance.
132+
self.assertIs(p1, p2)

0 commit comments

Comments
 (0)