Python 3.5+ 中的递归输入

Recursive Typing in Python 3.5+

在 Python 3.5 中,添加了类型注释(参见 here)。

是否有定义递归类型注释的方法,例如树状结构?

class Employee(object):
    def __init__(self, name: str, reports: List[Employee]):
       self.name = name
       self.reports = reports

在上面,注释 List[Employee] 似乎不起作用。 运行 代码导致此错误:

NameError: name 'Employee' is not defined

您可以使用 PEP 484

中定义的 Forward References

A situation where this occurs commonly is the definition of a container class, where the class being defined occurs in the signature of some of the methods. For example, the following code (the start of a simple binary tree implementation) does not work:

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

To address this, we write:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

It is allowable to use string literals as part of a type hint, for example:

class Tree:
    ...
    def leaves(self) -> List['Tree']: