【发布时间】:2021-06-26 13:48:25
【问题描述】:
我有一个例程来创建一个有效的 powerset。我为参数和返回值添加了一些类型注释,然后在结果上运行 Mypy。
Mypy 似乎与 stdlib 函数有问题,这是意料之中的吗?
(base) paddy3118@Paddy-G14:/mnt/c/Users/paddy/Google Drive/Code$ python -V
Python 3.8.5
(base) paddy3118@Paddy-G14:/mnt/c/Users/paddy/Google Drive/Code$ mypy -V
mypy 0.761
(base) paddy3118@Paddy-G14:/mnt/c/Users/paddy/Google Drive/Code$ uname -a
Linux Paddy-G14 4.19.128-microsoft-standard #1 SMP Tue Jun 23 12:58:10 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
(base) paddy3118@Paddy-G14:/mnt/c/Users/paddy/Google Drive/Code$ cat pwrset_mypy.py
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 30 14:59:19 2021
@author: Paddy3118
"""
from itertools import chain, combinations
from typing import List, Tuple
def powerset(s: List[int]) -> List[Tuple[int]]:
"""powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) ."""
return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))
if __name__ == '__main__':
assert powerset([0, 1, 2]) == [(), (0,), (1,), (2,), (0, 1), (0, 2),
(1, 2), (0, 1, 2)]
(base) paddy3118@Paddy-G14:/mnt/c/Users/paddy/Google Drive/Code$
(base) paddy3118@Paddy-G14:/mnt/c/Users/paddy/Google Drive/Code$ mypy --show-error-context --show-column-numbers --show-error-codes --pretty pwrset_mypy.py
pwrset_mypy.py: note: In function "powerset":
pwrset_mypy.py:13:37: error: Generator has incompatible item type "Iterator[Tuple[int, ...]]"; expected
"Iterable[Tuple[int]]" [misc]
return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))
^
Found 1 error in 1 file (checked 1 source file)
(base) paddy3118@Paddy-G14:/mnt/c/Users/paddy/Google Drive/Code$
``
【问题讨论】:
-
Tuple[int]表示包含 single int 的元组。 -
如何说明它返回零个或多个整数的元组列表?
-
就在你从mypy得到的错误信息中...
标签: python type-hinting mypy typechecking python-typing