【发布时间】:2019-11-18 14:43:27
【问题描述】:
我正在尝试定义一个函数,该函数可以接收对象容器的容器,并且我不在乎容器是元组还是列表。
(我知道我可以经历实现this 的麻烦,但我不想这样做,我仍然不确定这是否能解决我的问题。)
所以,我有以下代码:
from typing import Any, Union, List, Tuple
# (list or tuple) of Any
AnyBucket = Union[List[Any], Tuple[Any, ...]]
# should be (list or tuple) of (lists or tuples) of Any
AnyBuckets = Union[List[AnyBucket], Tuple[AnyBucket, ...]]
def takes_any_buckets(inpt: AnyBuckets) -> None:
print(inpt[0][0])
input_value: List[List[Any]] = [[1], [2]]
# Argument 1 to "takes_any_buckets" has incompatible type "List[List[Any]]";
# expected "Union[List[Union[List[Any], Tuple[Any, ...]]], Tuple[Union[List[Any], Tuple[Any, ...]], ...]]"
takes_any_buckets(input_value)
我有两个问题:
- 为什么 Mypy 会为此抛出错误?
- 我可以做些什么来获得我想要的功能(没有出现 Mypy 错误)?
(我不想只用# type: ignore 禁用错误,我想定义一个可以工作的类型。)
我对 (1) 的猜测是它与 Lists 是 invariant 有关,但是对于这个复杂的示例,我不知道如何。
除了可能实施前面提到的麻烦之外,我对 (2) 没有任何想法,这将使我摆脱 Unions,我怀疑这可能是问题的一部分。
【问题讨论】:
-
如果您对
tuple或list都满意,是否有理由不接受typing.Sequence(涵盖两者)或typing.Container(更广泛一点,接受非-像set)这样的可索引类型? -
谢谢;在过去的几分钟里,我自己发现了 Sequence(适用于我的情况)。如果您写它作为问题(2)的答案,我会暂时接受。
标签: python list tuples type-hinting mypy