22

My question is related with the new Python's type hints. I'm trying to add a type hint in an object's method who has a parameter of the same type of the object, but PyCharm are marking me as error (unresolved reference 'Foo'). The problem is as follows:

class Foo:

    def foo_method(self, other_foo: Foo):
        return "Hello World!"

So the question is how to define the type of other_foo parameter properly. Maybe __class__ is correct?

garciparedes
  • 1,749
  • 2
  • 18
  • 34

1 Answers1

43

Inside of the class, the class is not defined yet, causing a NameError (and PyCharm to complain).

To get around this, use a forwarding reference:

class Foo:
    def foo_method(self, other_foo: "Foo"):
        return "Hello World!"

Basically, if a type annotations is a string, it is evaled when the type is requested (in the global scope rather than the scope of the class Foo), so it can evaluate to the Foo class.


You can also use the annotations feature, which will turn all annotations into strings:

from __future__ import annotations

class Foo:
    def foo_method(self, other_foo: Foo):
        return "Hello World!"

# Foo.foo_method.__annotations__ == {'other_foo': 'Foo'}
# typing.get_type_hints(Foo.foo_method) == {'other_foo': Foo}

This is available since 3.7, and was slated to become the default behaviour in 3.10 but was postponed.

Artyer
  • 31,034
  • 3
  • 47
  • 75