Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cachetools timer with datetime.now #8459

Open
m3brown opened this issue Aug 1, 2022 · 2 comments
Open

Cachetools timer with datetime.now #8459

m3brown opened this issue Aug 1, 2022 · 2 comments

Comments

@m3brown
Copy link

m3brown commented Aug 1, 2022

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
@Akuli
Copy link
Collaborator

Akuli commented Aug 1, 2022

Arguably time.monotonic() would be better for some applications, because datetime.now() can go backwards. But I agree that both should be supported.

@michaeljpeake
Copy link

michaeljpeake commented Apr 18, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants