typeshed
typeshed copied to clipboard
Cachetools timer with datetime.now
A followup to the issue presented in #6953, I'm running into mypy errors when implementing a cache using the mechanism as defined in the cachetools documentation.
Cachetools documentation for TRLUCache with example that matches the implementation below.
My implementation
def expires_in_ttu(_key, value, now):
expires_in = value[1]
return now + timedelta(seconds=expires_in)
cache = TLRUCache(maxsize=10, ttu=expires_in_ttu, timer=datetime.now)
The mypy error:
Argument "timer" to "TLRUCache" has incompatible type "Callable[[Optional[tzinfo]], datetime]"; expected "Callable[[], float]"
Workaround:
We can use time.monotonic
instead of datetime.now
, but:
- the example in the docs use datetime.now
- datetime.now is arguably more familiar to most developers
Versions
- cachetools: 5.2.0
- types-cachetools: 5.2.1
Arguably time.monotonic()
would be better for some applications, because datetime.now()
can go backwards. But I agree that both should be supported.
I've have a similar problem with the ttl
variable. Maybe my own incompetance but I couldn't get my tests with freezegun working with time.monotonic
. Made the switch and can write the tests no problem but currently haven't to supress lint warnings for using timedelta
instead of float.