Issue
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?
Solution
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 eval
ed 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.
Answered By - Artyer Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.