Skip to content

Cachetools timer with datetime.now #8459

@m3brown

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

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