Skip to content

lru_cache classmethod: variable has type "Self" after assignment #18993

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

Open
Redoubts opened this issue Apr 28, 2025 · 1 comment · May be fixed by #19025
Open

lru_cache classmethod: variable has type "Self" after assignment #18993

Redoubts opened this issue Apr 28, 2025 · 1 comment · May be fixed by #19025
Labels
bug mypy got something wrong topic-self-types Types for self

Comments

@Redoubts
Copy link

https://mypy-play.net/?mypy=latest&python=3.11&gist=81326668cbc8056d8f3b44d3396ea0d0

If I have a lru_cache decorated classmethod, I noticed that I can get an error where the return type will be literally Self rather than the inferred class. I've seen a lot of discussion about lru_cache support, but it wasn't clear to me if this would be a dupe.

To Reproduce

from typing import Self
from functools import lru_cache

class A:
    @classmethod
    @lru_cache
    def a(cls) -> Self:
        return cls()
        
        
        
x = id(A)

if x == 1:
    aa = A.a()
else:
    aa = A() # Incompatible types in assignment (expression has type "A", variable has type "Self")  [assignment]

Expected Behavior

I expected this code to have no type errors

Actual Behavior

main.py:17: error: Incompatible types in assignment (expression has type "A", variable has type "Self") [assignment]
Found 1 error in 1 file (checked 1 source file)

Your Environment

mypy 1.15, python 3.11, stock config

@Redoubts Redoubts added the bug mypy got something wrong label Apr 28, 2025
@sterliakov
Copy link
Collaborator

This isn't specific to lru_cache, we leak self types from any method decorators apparently.

from typing import Callable, Self

class W[T]:
    def __init__(self, fn: Callable[..., T]) -> None: ...
    def __call__(self) -> T: ...
    
class Check:
    @W
    def foo(self) -> Self:
        ...

reveal_type(Check.foo())

https://mypy-play.net/?mypy=master&python=3.12&flags=strict&gist=674dee3d07ff816c3f12ee3ab5c86f1d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-self-types Types for self
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants