Python 输入参数可以是 None

Python typing for a parameter can be None

我正在尝试使用 python 键入注释创建树结构。代码是这样的:

from typing import List

class TNode:
    def __init__(self, parent: 'TNode', data: str, children: List['TNode'] = []):
        self.parent = parent
        self.data = data
        self.children = children


root = TNode(None, 'example')

但是代码存在类型不匹配的问题,Pycharm 会引发 Expected type 'TNode', got 'None' instead。有没有办法解决这个问题,或者有没有更好的方法来设计class构造函数?

如果你的父节点可以是None,你需要将参数标记为Optional或者显式使用Union[None, 'TNode']注解:

from typing import List, Optional

class TNode:
    def __init__(self, parent: Optional['TNode'], data: str, children: List['TNode'] = []) -> None:

旁注:您可能不想使用[]作为儿童的默认值。默认值计算 一次 并与函数对象一起存储,因此如果您要使用默认值并改变它,就会改变共享默认值。参见 "Least Astonishment" and the Mutable Default Argument

改为将 children 设置为默认 None 标记值:

class TNode:
    def __init__(
        self,
        parent: Optional['TNode'],
        data: str,
        children: Optional[List['TNode']] = None
    ) -> None:
        self.parent = parent
        self.data = data
        self.children = children or []

每当 children 参数为假值时,children or [] 表达式会将 self.children 设置为一个空列表,包括 None 和一个空列表。

我还为参数列表使用了不同的格式,更适合行长超过建议的 80 个字符行长度限制的类型注释参数。