diff --git a/docs/index.rst b/docs/index.rst index 147a19f..c9828b3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -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() @@ -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) diff --git a/tests/test_ttl.py b/tests/test_ttl.py index f677c9b..6e51a59 100644 --- a/tests/test_ttl.py +++ b/tests/test_ttl.py @@ -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))