Skip to content

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

Closed

Description

@Redoubts

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

Activity

  1. sterliakov commented on Apr 29, 2025

    @sterliakov
    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

  2. added a commit that references this issue on Jun 13, 2025
    6c3c4a7
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

    bugmypy got something wrongtopic-self-typesTypes for self

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions