Skip to content

Commit

Permalink
Fix #216: Add documentation and tests for using TTLCache with datetime.
Browse files Browse the repository at this point in the history
  • Loading branch information
tkem committed Sep 29, 2021
1 parent 7ae6ef5 commit c0162c5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
14 changes: 12 additions & 2 deletions docs/index.rst
Expand Up @@ -26,7 +26,7 @@ calls are provided, too.
.. testsetup:: *

import operator
from cachetools import cached, cachedmethod, LRUCache
from cachetools import cached, cachedmethod, LRUCache, TTLCache

from unittest import mock
urllib = mock.MagicMock()
Expand Down Expand Up @@ -122,7 +122,17 @@ computed when the item is inserted into the cache.

By default, the time-to-live is specified in seconds and
:func:`time.monotonic` is used to retrieve the current time. A
custom `timer` function can be supplied if needed.
custom `timer` function can also be supplied:

.. testcode::

from datetime import datetime, timedelta

cache = TTLCache(maxsize=10, ttl=timedelta(hours=12), timer=datetime.now)

The expression `timer() + ttl` at the time of insertion defines the
expiration time of a cache item, and must be comparable against
later results of `timer()`.

.. method:: expire(self, time=None)

Expand Down
12 changes: 12 additions & 0 deletions tests/test_ttl.py
Expand Up @@ -182,3 +182,15 @@ def test_ttl_tuple_key(self):
with self.assertRaises(KeyError):
cache[(1, 2, 3)]
self.assertNotIn((1, 2, 3), cache)

def test_ttl_datetime(self):
from datetime import datetime, timedelta

cache = TTLCache(maxsize=1, ttl=timedelta(days=1), timer=datetime.now)

cache[1] = 1
self.assertEqual(1, len(cache))
cache.expire(datetime.now())
self.assertEqual(1, len(cache))
cache.expire(datetime.now() + timedelta(days=1))
self.assertEqual(0, len(cache))

0 comments on commit c0162c5

Please sign in to comment.