小编use*_*495的帖子

为什么这个高阶函数无法通过mypy中的静态类型检查?

我正努力与mypy交涉。作为练习,我试图为一些常见的高阶函数找出正确的类型注释。但是我不太明白为什么下面的代码不进行检查。

test.py

from typing import Iterable, TypeVar, Callable

T1 = TypeVar('T1')
T2 = TypeVar('T2')

def chain(
        functions: Iterable[Callable[[T1], T1]]
    ) -> Callable[[T1], T1]:

    def compose(
            f: Callable[[T1], T1],
            g: Callable[[T1], T1]
        ) -> Callable[[T1], T1]:
        def h(x: T1) -> T1:
            return g(f(x))
        return h

    def identity(x: T1) -> T1:
        return x

    return reduce(functions, compose, identity)

def reduce(
        items: Iterable[T1], 
        op:    Callable[[T2, T1], T2],
        init:  T2
    ) -> T2:
    for item in items:
        init = op(init, item)
    return init

def add_one(x): …
Run Code Online (Sandbox Code Playgroud)

python functional-programming python-3.x mypy

7
推荐指数
1
解决办法
119
查看次数

标签 统计

functional-programming ×1

mypy ×1

python ×1

python-3.x ×1