微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

检查 stdlib 函数时出现 Mypy 错误?

如何解决检查 stdlib 函数时出现 Mypy 错误?

我有一个程序来创建一个有效的 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,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,1),2),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,...] 而不是 Tuple[int]

def powerset(s: List[int]) -> List[Tuple[int,...]]:
    """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,3) ."""
    return list(chain.from_iterable(combinations(s,r) for r in range(len(s)+1)))

除非调用者知道这些是元组很重要,否则另一种选择是将它们指定为 Iterable[int]s:

def powerset(s: List[int]) -> List[Iterable[int]]:
    """powerset([1,r) for r in range(len(s)+1)))

请注意,Tuple[int] 特别是包含单个 int 的元组,而 Iterable[int] 是包含任意数量的 int 的任何可迭代对象。元组类型声明为元组的每个位置采用一个类型参数——因为每个单独的元组都是不可变的,所以可以注释每个位置并知道类型将被保留,因此您可以使用 Tuple[int,int]Tuple[int,str]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。