The docs for TLRU are in correct
Closed this issue · 3 comments
Describe the bug
The documentation in https://github.com/tkem/cachetools/blob/master/docs/index.rst#cache-implementations refers to
from datetime import datetime, timedelta
def my_ttu(_key, value, now):
# assume value.ttl contains the item's time-to-live in hours
return now + timedelta(hours=value.ttl)
cache = TLRUCache(maxsize=10, ttu=my_ttu, timer=datetime.now)
Expected result
The issue here is that the ttu
is a Callable that returns a float
not a datetime
and same with timer
.
It would be nice if the docs mentioned these types but at the least the example should probably read something like.
from datetime import datetime, timedelta
def my_ttu(_key, value, now):
# assume value.ttl contains the item's time-to-live in hours
return now + timedelta(hours=value.ttl).seconds
cache = TLRUCache(maxsize=10, ttu=my_ttu)
So now in this time, the now is provided by the time.monotonic
and you can add the seconds
from the timedelta
to it.
Basically, the same holds for TLRUCache
as stated in the TTLCache
docs:
A custom timer function can also be supplied, which does not have to return seconds, or even a numeric value. 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(), but ttl does not necessarily have to be a number, either.
So, to give a more complete example, with hours replaced by seconds for convenience:
from cachetools import TLRUCache
from collections import namedtuple
from datetime import datetime, timedelta
from time import sleep
Value = namedtuple('Value', ['value', 'ttl'])
def my_ttu(_key, value, now):
# assume value.ttl contains the item's time-to-live in seconds
return now + timedelta(seconds=value.ttl)
cache = TLRUCache(maxsize=10, ttu=my_ttu, timer=datetime.now)
print(cache)
cache[0] = Value(0, 1)
print(cache)
sleep(1.5)
print(cache)
results in
TLRUCache({}, maxsize=10, currsize=0)
TLRUCache({0: Value(value=0, ttl=1)}, maxsize=10, currsize=1)
TLRUCache({}, maxsize=10, currsize=0)
So I think the docs are correct, but maybe should be extended somewhat (as docs always should).
Huh... Yea I didn't realize it could be both. I would think whatever types are possible should probably have examples with them. Thanks for the update. Also love cachetools.