Question

  • Creator
    Topic
  • #2141903

    Python type hinting own class in method

    by elenaflorence ·

    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

You are posting a reply to: Python type hinting own class in method

The posting of advertisements, profanity, or personal attacks is prohibited. Please refer to our Community FAQs for details. All submitted content is subject to our Terms of Use.

All Answers

Share your knowledge