0

I was wodering if there is a way to use a class as type for typehinting a method of the class.

This example gives a NameError since Monomial is not defined yet:

class Monomial():
    def __init__(self, coef: int, grade: int) -> None:
        self.grade = grade
        self.coef = coef

    def product(self, other:Monomial) -> Monomial:
        return Monomial(self.coef*other.coef, self.grade+other.grade)

Typehinting works perfectly outside:

def product(firs:Monomial, other:Monomial) -> Monomial:
    return Monomial(first.coef*other.coef, first.grade+other.grade)

I was wondering if there is a keyword that I may use to hint the type or another solution. It would be useful since I am using mypy as type checker.

I know I could simply not state the type but I would like to find a solution so I can check the type. Thanks in advance :)

Pablo
  • 49
  • 1
  • 5

1 Answers1

1

You must put the forward references to "Monomial" in quotes like this:

class MyClass:
    def doit(self) -> 'MyClass':
        pass

See https://www.python.org/dev/peps/pep-0484/#forward-references for details.

Shaheed Haque
  • 644
  • 5
  • 14