Skip to content

Commit

Permalink
Ensure caches are removed from what is pickled
Browse files Browse the repository at this point in the history
  • Loading branch information
mhvk committed Oct 9, 2023
1 parent 81fb4b1 commit 38fe2ea
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
6 changes: 6 additions & 0 deletions astropy/time/core.py
Expand Up @@ -1653,6 +1653,12 @@ def cache(self):
for instance in self._id_cache.values():
del instance._time.cache

Check warning on line 1654 in astropy/time/core.py

View check run for this annotation

Codecov / codecov/patch

astropy/time/core.py#L1653-L1654

Added lines #L1653 - L1654 were not covered by tests

def __getstate__(self):
# For pickling, we remove the cache from what's pickled
state = super().__getstate__().copy()
state.pop("_id_cache", None)
return state

Check warning on line 1660 in astropy/time/core.py

View check run for this annotation

Codecov / codecov/patch

astropy/time/core.py#L1658-L1660

Added lines #L1658 - L1660 were not covered by tests

def __getattr__(self, attr):
"""
Get dynamic attributes to output format or do timescale conversion.
Expand Down
6 changes: 6 additions & 0 deletions astropy/time/formats.py
Expand Up @@ -288,6 +288,12 @@ def cache(self):
"""
return defaultdict(dict)

def __getstate__(self):
# For pickling, we remove the cache.
state = super().__getstate__().copy()
state.pop("cache", None)
return state

Check warning on line 295 in astropy/time/formats.py

View check run for this annotation

Codecov / codecov/patch

astropy/time/formats.py#L293-L295

Added lines #L293 - L295 were not covered by tests

def _check_val_type(self, val1, val2):
"""Input value validation, typically overridden by derived classes."""
# val1 cannot contain nan, but val2 can contain nan
Expand Down
14 changes: 14 additions & 0 deletions astropy/time/tests/test_pickle.py
Expand Up @@ -25,3 +25,17 @@ def test_pickle(self):
t2d = pickle.dumps(t2, prot)
t2l = pickle.loads(t2d)
assert t2l == t2

def test_cache_not_shared(self):
t = Time(["2001:020", "2001:040", "2001:060", "2001:080"], out_subfmt="date")
# Ensure something is in the cache.
t.value
assert "format" in t.cache
td = pickle.dumps(t)
assert "format" in t.cache
tl = pickle.loads(td)
assert "format" in t.cache
assert "format" not in tl.cache
t[0] = "1999:099"
assert t.value[0] == "1999:099"
assert tl.value[0] == "2001:020"

0 comments on commit 38fe2ea

Please sign in to comment.