Skip to content

Commit

Permalink
allow cache to contain non-weakref-able objects
Browse files Browse the repository at this point in the history
  • Loading branch information
braingram committed May 13, 2024
1 parent 7871f79 commit 401edea
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
12 changes: 12 additions & 0 deletions asdf/_tests/test_lazy_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,15 @@ def test_cache_frees_deleted_object(cache_test_tree_path):
af["a"]
# but can get 'b'
assert af["b"][0] is af["b"][1]


def test_cache_non_weakref():
"""
Test that an object that cannot weak reference can be cached
"""
tagged_node = {}
obj = complex(1, 1)
cache_item = asdf.lazy_nodes._TaggedObjectCacheItem(tagged_node, obj)
del obj
gc.collect()
assert cache_item.custom_object == complex(1, 1)
6 changes: 5 additions & 1 deletion asdf/lazy_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ class _TaggedObjectCacheItem:

def __init__(self, tagged_node, custom_object):
self.tagged_node = tagged_node
self._custom_object_ref = weakref.ref(custom_object)
try:
self._custom_object_ref = weakref.ref(custom_object)
except TypeError:
# if a weakref is not possible, store the object
self._custom_object_ref = lambda obj=custom_object: obj

@property
def custom_object(self):
Expand Down

0 comments on commit 401edea

Please sign in to comment.