• Creator
  • #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): = id

    def __eq__(self, other):
    return ==
    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 ==
    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 ==
    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?

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