Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend the Cache class to function like a dictionary #363

Merged
merged 2 commits into from
Jul 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions src/toast/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,38 @@ def __init__(self, pymem=False):
self._shapes = dict()
self._aliases = dict()

def __getitem__(self, key):
return self.reference(key)

def __setitem__(self, key, value):
self.put(key, value, replace=True)

def __delitem__(self, key):
self.destroy(key)

def __contains__(self, key):
return self.exists(key)

def __len__(self):
return len(self.keys())

def __iter__(self):
class CacheIterator:
def __init__(self, cache):
self.cache = cache
self.keys = cache.keys()

def __iter__(self):
return self

def __next__(self):
if len(self.keys) == 0:
raise StopIteration
key = self.keys.pop()
return self.cache[key]

return CacheIterator(self)

def clear(self, pattern=None):
"""Clear one or more buffers.

Expand Down Expand Up @@ -237,7 +269,7 @@ def destroy(self, name):
return
names = list(self._buffers.keys())
if name not in names:
raise RuntimeError("Data buffer {} does not exist".format(name))
raise KeyError("Data buffer {} does not exist".format(name))

# Remove aliases to the buffer
aliases_to_remove = []
Expand Down Expand Up @@ -292,7 +324,7 @@ def reference(self, name):
"""
# First check that it exists
if not self.exists(name):
raise RuntimeError("Data buffer (nor alias) {} does not exist".format(name))
raise KeyError("Data buffer (nor alias) {} does not exist".format(name))
realname = name
if name in self._aliases:
# This is an alias
Expand Down
15 changes: 15 additions & 0 deletions src/toast/tests/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ def tearDown(self):
del self.cache
del self.pycache

def test_dict_interface(self):
cache = Cache()
cache["aaa"] = np.arange(10)
cache["ccc"] = np.arange(10) + 10
self.assertTrue("aaa" in cache)
self.assertFalse("bbb" in cache)
self.assertEqual(len(cache), 2)
n = 0
for x in cache:
n += 1
self.assertEqual(len(cache), n)
del cache["aaa"]
self.assertEqual(len(cache), n - 1)
return

def test_refcount(self):
buf = AlignedF64.zeros(self.nsamp)
# print("REFCNT: ", sys.getrefcount(buf), flush=True)
Expand Down