gpt4 book ai didi

python - 嵌套列表的函数返回值的静态类型

转载 作者:行者123 更新时间:2023-12-01 09:15:43 25 4
gpt4 key购买 nike

我有一个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

我希望生成列表返回一个列表,其中包括一个可能包含 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]]]

关于python - 嵌套列表的函数返回值的静态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51280767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com