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?
PEP 484, which provides a specification about what a type system should look like in Python3, introduced the concept of type hints.
Syntax of the Python type() function The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
First, extract the class body as string. Second, create a class dictionary for the class namespace. Third, execute the class body to fill up the class dictionary. Finally, create a new instance of type using the above type() constructor.
Inside of the class, the class is not defined yet, causing a NameError
(and PyCharm to complain).
To get around this, use forward declarations:
class Foo:
def foo_method(self, other_foo: "Foo"):
return "Hello World!"
Basically, if a type annotations is a string, it is eval
ed after the whole module is loaded, so it can evaluate to the Foo
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With