Skip to content
Snippets Groups Projects
Commit 0de46cca authored by Paul McCarthy's avatar Paul McCarthy :mountain_bicyclist:
Browse files

ENH: Cache has an lru option

parent 60a468c7
No related branches found
No related tags found
No related merge requests found
...@@ -42,14 +42,20 @@ class Cache(object): ...@@ -42,14 +42,20 @@ class Cache(object):
raised. raised.
""" """
def __init__(self, maxsize=100): def __init__(self, maxsize=100, lru=False):
"""Create a ``Cache``. """Create a ``Cache``.
:arg maxsize: Maximum number of items allowed in the ``Cache`` before :arg maxsize: Maximum number of items allowed in the ``Cache`` before
it starts dropping old items it starts dropping old items
:arg lru: (least recently used) If ``False`` (the default), items
are dropped according to their insertion time. Otherwise,
items are dropped according to their most recent access
time.
""" """
self.__cache = collections.OrderedDict() self.__cache = collections.OrderedDict()
self.__maxsize = maxsize self.__maxsize = maxsize
self.__lru = lru
def put(self, key, value, expiry=0): def put(self, key, value, expiry=0):
...@@ -94,14 +100,26 @@ class Cache(object): ...@@ -94,14 +100,26 @@ class Cache(object):
else: else:
entry = self.__cache[key] entry = self.__cache[key]
# Check to see if the entry
# has expired
now = time.time()
if entry.expiry > 0: if entry.expiry > 0:
if time.time() - entry.storetime > entry.expiry: if now - entry.storetime > entry.expiry:
self.__cache.pop(key) self.__cache.pop(key)
if defaultSpecified: return default if defaultSpecified: return default
else: raise Expired(key) else: raise Expired(key)
# If we are an lru cache, update
# this entry's expiry, and update
# its order in the cache dict
if self.__lru:
entry.storetime = now
self.__cache.pop(key)
self.__cache[key] = entry
return entry.value return entry.value
...@@ -134,7 +152,7 @@ class Cache(object): ...@@ -134,7 +152,7 @@ class Cache(object):
- ``True`` if a default argument was specified, ``False`` - ``True`` if a default argument was specified, ``False``
otherwise. otherwise.
- The specifeid default value, or ``None`` if it wasn't - The specified default value, or ``None`` if it wasn't
specified. specified.
""" """
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment