#๐Ÿ”’ MyPy errors calling a classmethod from a classmethod

6 messages ยท Page 1 of 1 (latest)

storm ginkgo
#

Sample code:

from typing import Self


class Foo:
    a: int

    def __init__(self, a: int):
        self.a = a

    @classmethod
    def m1(cls) -> Self:
        return Foo.m2()

    @classmethod
    def m2(cls) -> Self:
        return cls(100)


print(f"m2: {Foo.m2().a}")
print(f"m1: {Foo.m1().a}")

The code seems to work fine, both m1 and m2 print 100. However, MyPY doesn't seem to know that Foo and Self are the same type:

a.py:12: error: Incompatible return value type (got "Foo", expected "Self")  [return-value]
Found 1 error in 1 file (checked 1 source file)

What is the proper way to type hint this? Or is there a better way to write it?

left dockBOT
#

@storm ginkgo

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

storm ginkgo
#

Discovered a solution at https://github.com/python/mypy/issues/16558: Self is a distinct type, but cls has the type Self, so this is accepted:

    @classmethod
    def m1(cls) -> Self:
        return type(cls).m2()

Seems a bit hacky but it works

GitHub

Optional static typing for Python. Contribute to python/mypy development by creating an account on GitHub.

#

!close

left dockBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.