type-hinting - 向接受任何可迭代并返回压缩值的函数添加类型提示

标签 type-hinting mypy python-3.10

我有以下工作代码来解决 Advent of Code 2021 day 1 (由于 itertools.pairwise ,需要 Python 3.10 ),但我对如何正确添加类型提示感到困惑。

from itertools import pairwise, tee
from typing import Iterator, TypeVar, Tuple, Generator

_T_co = TypeVar("_T_co", covariant=True)

def tripletwise(iterable: Iterator[_T_co]) -> zip[Tuple[_T_co, _T_co, _T_co]]:
    """tripletwise('ABCDEFG') --> ABC BCD CDE DEF EFG"""
    a, b, c = tee(iterable, 3)
    next(b, None)
    next(c, None)
    next(c, None)
    return zip(a, b, c)


def sonar_sweep(sea_floor_depths: Generator[int, None, None], part: int = 1) -> int:
    if part == 1:
        return sum(b > a for a, b in pairwise(sea_floor_depths))
    return sonar_sweep((a + b + c for a, b, c in tripletwise(sea_floor_depths)), part=1)


def sea_floor_depths(report: str) -> Generator[int, None, None]:
    return map(int, report.splitlines())


def main(part: int = 1) -> int:
    with open("2021/data/day01.txt") as f:
        report = f.read()
    return sonar_sweep(sea_floor_depths(report), part)


if __name__ == "__main__":
    report = """199
200
208
210
200
207
240
269
260
263"""
    assert sonar_sweep(sea_floor_depths(report), part=1) == 7
    assert sonar_sweep(sea_floor_depths(report), part=2) == 5
    assert list(tripletwise("ABCDEFG")) == [
        ("A", "B", "C"),
        ("B", "C", "D"),
        ("C", "D", "E"),
        ("D", "E", "F"),
        ("E", "F", "G"),
    ]
    assert list(tripletwise(sea_floor_depths(report))) == [
        (199, 200, 208),
        (200, 208, 210),
        (208, 210, 200),
        (210, 200, 207),
        (200, 207, 240),
        (207, 240, 269),
        (240, 269, 260),
        (269, 260, 263),
    ]

    print(main())
    print(main(part=2))

目前,当我对此运行 mypy 时,我得到:

2021/day01.py:22: error: Incompatible return value type (got "map[int]", expected "Generator[int, None, None]")
2021/day01.py:44: error: Argument 1 to "tripletwise" has incompatible type "str"; expected "Iterator[<nothing>]"

我想用类型提示来表明tripletwise()可以接受任何可迭代的(例如字符串"ABCDEFG"sea_floor_depths的输出(报告))。我也不确定 sea_floor_depths() 的正确返回类型。

最佳答案

对于第一个错误,map builtin 仅记录为返回迭代器,因此您可以使用的最具体的类型提示是 Iterator[int]GeneratorIterator 的子类型,仅在使用生成器表达式或生成器函数时出现,而您的函数则不会。

对于第二个错误,问题在于 str 本身并不是 iterators ,但只是 iterables ,因此适当的类型提示将是 Iterable[_T_co]

关于type-hinting - 向接受任何可迭代并返回压缩值的函数添加类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70191772/

相关文章:

python - 如何在不扰乱 mypy 的情况下将元组用作 attr.ib 的转换器?

pytest - 尝试使用 pytest 在 python 3.10 上执行测试时出错

Python 结构模式匹配

python - 如何限制可以传递给方法参数的允许值(使用类型提示允许静态代码分析)

python - 关闭 'Python version 3.5 does not support variable annotations' 错误信息

java - Enunciate 中收集的 TypeHint

python - 使用 Python 类型注释声明通用 Mapping 子类?

python-3.x - 带有异常处理的 Python 类型

python - 什么类型提示同时包含列表和元组?

python - 结构模式匹配默认情况下如何访问匹配值?