Skip to content

Cachetools timer with datetime.now #8459

Open

Description

@m3brown

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

Activity

  1. Akuli commented on Aug 1, 2022

    @Akuli
    Collaborator

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

  2. michaeljpeake commented on Apr 18, 2023

    @michaeljpeake

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions