Edit: I notice people commenting about how the type hint should not be used with __eq__
, and granted, it shouldn't. But that's not the point of my question. My question is why can't the class be used as type hint in the method parameters, but can be used in the method itself?
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?