[英]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.