Search code examples
pythonpycharmpython-typing

When returning an instance of class Foo using self.__class__(), why does PyCharm think the type should be Optional[Type[Foo]]?


I have a class Foo that has a method that returns another Foo instance.

from __future__ import annotations

class Foo:
    def get_other_foo(self) -> Foo:
        return self.__class__()

(The __future__ import is to make the Foo annotation on the method work in Python 3.7.)

This works, and MyPy doesn't flag any errors in the file. However, PyCharm highlights the return value in yellow, and when I hover over it I get the warning "Expected type 'Foo', got 'Optional[Type[Foo]]' instead".

I considered hard-coding Foo inside the method, like this:

from __future__ import annotations

class Foo:
    def get_other_foo(self) -> Foo:
        return Foo()

This also works, and silences the PyCharm warning. However, in a subclass this would return an instance of Foo instead of an instance of the subclass, so I am reluctant to do this.

Why does PyCharm think the return type should be Optional[Type[Foo]] in my first example? And is there a way to fix the PyCharm warning while keeping the ability of get_other_foo() to return a subclass instance when called from a subclass?


Solution

  • it's a known issue https://youtrack.jetbrains.com/issue/PY-37935, please vote!