使用默认值 None 键入类属性 - 最佳实践?

问题描述 投票:0回答:0

我正在尝试向遗留 Python 2.7 代码引入类型提示。许多类使用默认值

None
声明类属性(以避免可变默认值),然后在构造函数中分配值。

对于下面的示例,我无法想出一种正确推断

_myList
_myList2
并且不会出错的方法。

from typing import Optional, List

class Myclass(object):
    _myList = None  # type: Optional[List]  # T1
    _myList2 = None  # type: Optional[List]  # T2
    _myList3 = None  # type: Optional[List]  # T3
    
    def __init__(self, inList=None):
        # type: (Optional[List]) -> None   # T4
        self._myList = inList or []  # type: List  # T5
        self._myList2 = []  # type: List  # T6
    
    def show(self):
        print(self._myList)
        print(self._myList2)
        print(self._myList3)

Pyright 在这个例子中给出了 T1 和 T2 行的错误 (

Expression of type "None" cannot be assigned to declared type "List[Unknown]"
)。如果删除行 T1-T3 上的类型提示,它们将保留。

从 T5 和 T6 行中删除类型提示会清除错误,但

show(self)
中的类型不再被推断为
List
,尽管在构造函数中已分配。这是一个问题,因为其他代码假定字段不是
None
.

在这种情况下添加类型提示的正确方法是什么?有没有一种方法可以在不改变类结构的情况下完成?

我看过像thisthis这样的问题,但没有找到好的答案。欢迎解释 Python 3 中的标准,但请确保与 Python 2.7 的兼容性。

python python-2.7 typing pylance pyright
© www.soinside.com 2019 - 2024. All rights reserved.