Skip to content

Commit

Permalink
Update expire docs.
Browse files Browse the repository at this point in the history
  • Loading branch information
tkem committed Aug 18, 2024
1 parent 7be40f0 commit 8a38daf
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ method calls.
from unittest import mock
urllib = mock.MagicMock()

import time


Cache implementations
=====================
Expand Down Expand Up @@ -153,6 +155,8 @@ computed when the item is inserted into the cache.
items that have expired by the current value returned by
:attr:`timer`.

:returns: An iterable of expired `(key, value)` pairs.

.. autoclass:: TLRUCache(maxsize, ttu, timer=time.monotonic, getsizeof=None)
:members: popitem, timer, ttu

Expand Down Expand Up @@ -193,6 +197,8 @@ computed when the item is inserted into the cache.
items that have expired by the current value returned by
:attr:`timer`.

:returns: An iterable of expired `(key, value)` pairs.


Extending cache classes
=======================
Expand All @@ -217,6 +223,31 @@ cache, this can be achieved by overriding this method in a subclass:
>>> c['c'] = 3
Key "a" evicted with value "1"

With :class:`TTLCache` and :class:`TLRUCache`, items may also be
removed after they expire. In this case, :meth:`popitem` will *not*
be called, but :meth:`expire` will be called from the next mutating
operation and will return an iterable of the expired `(key, value)`
pairs. By overrding :meth:`expire`, a subclass will be able to track
expired items:

.. doctest::
:pyversion: >= 3

>>> class ExpCache(TTLCache):
... def expire(self, time=None):
... items = super().expire(time)
... print(f"Expired items: {items}")
... return items

>>> c = ExpCache(maxsize=10, ttl=1.0)
>>> c['a'] = 1
Expired items: []
>>> c['b'] = 2
Expired items: []
>>> time.sleep(1.5)
>>> c['c'] = 3
Expired items: [('a', 1), ('b', 2)]

Similar to the standard library's :class:`collections.defaultdict`,
subclasses of :class:`Cache` may implement a :meth:`__missing__`
method which is called by :meth:`Cache.__getitem__` if the requested
Expand Down

0 comments on commit 8a38daf

Please sign in to comment.