Yakuza Yakuza - 1 year ago 82
Python Question

Type hint for argument of type A in method of class A

I'm trying to make use of type hints in Python 3.5.1 with following code:

>>> class A:
... def a(self, i: int, b: A):
... pass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in A
NameError: name 'A' is not defined

I guess it's problem with scoping that type A is not yet fully constructed while parsing type A, but I fail to understand why such a syntax is not OK. Is there some way to express it otherwise or it's simply illegal construct?

I wanted to use this syntax hint in base class that could compose derived classes in tree-like hierarchy.

Answer Source

Try this:

class A:

    def a(self, i: int, b: 'A'):

For more information take a look here