简体   繁体   English

如何正确键入注释构建序列列表的表达式?

[英]How can I properly type annotate an expression that builds a List of Sequences?

I want to build a list that contains tuples or lists of strings.我想构建一个包含元组或字符串列表的列表。 I want:我想:

x = [('foo',)] + [('bar', 'baz')]

(Obviously I could create a single list initially instead of splicing two lists together in this simplified example. Pretend that one of them is the result of a function call or list comprehension.) (显然,我最初可以创建一个列表,而不是在这个简化的示例中将两个列表拼接在一起。假设其中一个是函数调用或列表理解的结果。)

mypy complains: mypy抱怨:

 List item 0 has incompatible type "Tuple[str, str]"; expected "Tuple[str]"

Okay, it infers that I'm adding a Tuple[str] to a Tuple[str, str] and doesn't like that I'm creating a heterogeneous list.好的,它推断我正在将一个Tuple[str]添加到一个Tuple[str, str]并且不喜欢我正在创建一个异构列表。 However, the list is homogeneous from a different perspective;但是,从不同的角度来看,该列表是同质的; I want it to be a typing.List[typing.Sequence[str]] .我希望它是一个typing.List[typing.Sequence[str]]

Is there a nice way to convince mypy of this?有没有一种好方法可以让mypy相信这一点? I tried annotating x :我尝试注释x​​ :

x: typing.List[typing.Sequence[str]] = [('foo',)] + [('bar', 'baz')]

but mypy still complains.mypy仍然抱怨。 It additionally complains:它还抱怨:

 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

Breaking up the expression works:分解表达式的工作原理:

x: typing.List[typing.Sequence[str]] = []
x.append(('foo',))
x.append(('bar', 'baz'))

or adding explicit casts:或添加显式演员表:

x = ([typing.cast(typing.Sequence[str], ('foo',))]
     + [typing.cast(typing.Sequence[str], ('bar', 'baz'))])

but both workarounds are much uglier than I'd like.但这两种解决方法都比我想要的要丑陋得多。

I realized that I only need to add an explicit cast for the first expression:我意识到我只需要为第一个表达式添加显式转换:

x = ([typing.cast(typing.Sequence[str], ('foo',))]
     + [('bar', 'baz')])

which isn't quite as nice as being able to annotate x , but at least it's in only one place.这不如能够注释x好,但至少它只在一个地方。

Can you give a static type to your 2 lists?你能给你的2个列表一个静态类型吗? I have tried this and the syntax checker does not complain我已经尝试过了,语法检查器没有抱怨

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM