[英]How can I properly type annotate an expression that builds a List of Sequences?
我想构建一个包含元组或字符串列表的列表。 我想:
x = [('foo',)] + [('bar', 'baz')]
(显然,我最初可以创建一个列表,而不是在这个简化的示例中将两个列表拼接在一起。假设其中一个是函数调用或列表理解的结果。)
mypy
抱怨:
List item 0 has incompatible type "Tuple[str, str]"; expected "Tuple[str]"
好的,它推断我正在将一个Tuple[str]
添加到一个Tuple[str, str]
并且不喜欢我正在创建一个异构列表。 但是,从不同的角度来看,该列表是同质的; 我希望它是一个typing.List[typing.Sequence[str]]
。
有没有一种好方法可以让mypy
相信这一点? 我尝试注释x
:
x: typing.List[typing.Sequence[str]] = [('foo',)] + [('bar', 'baz')]
但mypy
仍然抱怨。 它还抱怨:
Incompatible types in assignment (expression has type "List[Tuple[str]]", variable has type "List[Sequence[str]]") "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance Consider using "Sequence" instead, which is covariant
分解表达式的工作原理:
x: typing.List[typing.Sequence[str]] = []
x.append(('foo',))
x.append(('bar', 'baz'))
或添加显式演员表:
x = ([typing.cast(typing.Sequence[str], ('foo',))]
+ [typing.cast(typing.Sequence[str], ('bar', 'baz'))])
但这两种解决方法都比我想要的要丑陋得多。
我意识到我只需要为第一个表达式添加显式转换:
x = ([typing.cast(typing.Sequence[str], ('foo',))]
+ [('bar', 'baz')])
这不如能够注释x
好,但至少它只在一个地方。
你能给你的2个列表一个静态类型吗? 我已经尝试过了,语法检查器没有抱怨
from typing import List, Sequence
list_one : List[Sequence[str]] = [('foo',)]
list_two : List[Sequence[str]] = [('bar', 'baz')]
x: List[Sequence[str]] = list_one + list_two
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.