Skip to content

My 1.5.1 gets confused when a class variable references a method from another class that returns Self. #15934

Description

@benwah

Bug Report

When you define a class variable on a class that references a method that returns Self from another class, MyPy thinks that Self is the class where the method is referenced/

To Reproduce

from typing import Self


class Foo:
    def foo(self) -> Self:
        return self


class Ben:
    MY_MAP = {
        "foo": Foo.foo,
    }

    @classmethod
    def doit(cls) -> Foo:
        foo_method = cls.MY_MAP["foo"]
        return foo_method(Foo())


assert isinstance(Ben.doit(), Foo)

Expected Behavior

Mypy should not detect any errors.

Actual Behavior

ben.py:17: error: Incompatible return value type (got "Ben", expected "Foo")  [return-value]
ben.py:17: error: Argument 1 has incompatible type "Foo"; expected "Ben"  [arg-type]

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files):
plugins = [
  "pydantic.mypy"
]
explicit_package_bases = true
python_version = "3.11"
check_untyped_defs = true
exclude = '''
(?x)(
    ^.*flycheck.*$
    | ^.*#.*$
  )
'''
  • Python version used: 3.11

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-self-typesTypes for self

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions