Skip to content

[functools] Allow method override with @cache decorator#15238

Merged
srittau merged 1 commit intopython:mainfrom
emmanuel-ferdman:main
Jan 9, 2026
Merged

[functools] Allow method override with @cache decorator#15238
srittau merged 1 commit intopython:mainfrom
emmanuel-ferdman:main

Conversation

@emmanuel-ferdman
Copy link
Contributor

PR Summary

When you use the @cache decorator on a method and then override that method in a subclass with a more specific return type, mypy incorrectly rejects it. For example, if a parent class has a cached method returning Fruit and a child class overrides it to return Apple (a subclass of Fruit), this should be valid but wasn't. The fix changes _lru_cache_wrapper to use a covariant type parameter, which is safe because the type only appears in return positions. This matches how cached_property already works in the same file.

Fixes #15139.

Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com>
@github-actions
Copy link
Contributor

github-actions bot commented Jan 8, 2026

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

Copy link
Collaborator

@srittau srittau left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@srittau srittau merged commit f30821c into python:main Jan 9, 2026
63 checks passed
@ktbarrett
Copy link
Contributor

@emmanuel-ferdman Saw this randomly browsing the repo. Just wanted to make sure you know that using @cache on methods keeps all instances alive forever (or until the cache is cleared).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Maybe functools._lru_cache_wrapper should be covariant

3 participants