函数 return 嵌套列表值的静态类型

Static typing for function return value of nested list

我有一个Python代码:

from typing import List, Optional


class MyClass:
    pass


def generate_list() -> List[List[Optional[MyClass]]]:
    my_list = [[None for _ in range(10)] for _ in range(10)]
    # assignments might be extended in the future
    my_list[0][0] = MyClass()
    return my_list

我想生成列表 return 一个列表,其中包括一个可能包含 None 或 MyClass 对象的列表。 简化的列表可能如下所示

[[None, None, <my_class_object>], [<my_class_object>, None, <my_class_object>]]

现在 mypy 在线报错

my_list[0][0] = MyClass()

有留言

error: Incompatible return value type (got "List[List[None]]", expected "List[List[Optional[MyClass]]]")

我想我错过了什么,或者它甚至可能无法做我想做的事。

这是mypy的推断没有推断出你想要的情况。来自文档:

Mypy considers the initial assignment as the definition of a variable. If you do not explicitly specify the type of the variable, mypy infers the type based on the static type of the value expression

https://mypy.readthedocs.io/en/latest/type_inference_and_annotations.html

my_list 被推断为 List[List[None]] 因为这是表达式的类型。要解决此问题,您必须将其注释为 List[List[Optional[MyClass]]]