嵌套列表的Python类型注释

问题描述 投票:5回答:1

我想注释我的返回类型,它恰好是包含整数列表的列表。此注释是否为:List[List[int]]可以吗?这是我的返回类型的确切示例:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
python annotations typing
1个回答
0
投票

是,List[List[int]]是正确的类型。

作为一个旁注,每当不确定类型时,都可以定义该变量,然后使用Mypy reveal_type方法让它猜测正确的类型。例如:

> cat foo.py
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
reveal_type(a)

> mypy foo.py
1.py:2: note: Revealed type is 'builtins.list[builtins.list*[builtins.int]]'

告诉您a的类型为List[List[int]]。注意,reveal_type不是有效的函数;这是Mypy中内置的一种特殊语法。如果您尝试在Python中运行foo.py,它将抛出NameError

有关更多信息,请考虑阅读Mypy docs

© www.soinside.com 2019 - 2024. All rights reserved.