Question

Python type hinting own class in method

Python type hinting has proven very useful for me when working with PyCharm. However, I've come across behaviour I find strange, when trying to use a class' own type in its methods.

For example:

class Foo:

def __init__(self, id):
self.id = id
pass

def __eq__(self, other):
return self.id == other.id
Here, when typing other., the property id is not offered automatically. I was hoping to solve it by defining __eq__ as follows:

def __eq__(self, other: Foo):
return self.id == other.id
However, this gives NameError: name 'Foo' is not defined. But when I use the type within the method, id is offered after writing other.:

def __eq__(self, other):
other: Foo
return self.id == other.id
My question is, why is it not possible to use the class' own type for type hinting the parameters, while it is possible within the method?
Python https://bit.ly/3iZ3cZD
Thread display: Collapse - | Expand +

All Answers

Share your knowledge

Related Discussions

Related Forums