有没有相当于 Typescript `typeof` 或 C++ `decltype` 的 Python 语言?

问题描述 投票:0回答:1

假设我们有一个函数,例如

reduce
,它接受回调,例如
combiner
。如果我有一个示例回调函数
exampleReducer
,我希望避免手动编写回调的类型,而使用
exampleReducer
的类型。

在 C++ 中,我可以使用

exampleReducer
:
 获取 
decltype

的类型
#include <iostream>
#include <vector>
using namespace std;;

float exampleReducer(float x, float y) {
    return x+y;
}

auto reduce(decltype(exampleReducer) reducer, vector<float> numbers) { 
    auto result = numbers[0];
    for (auto x: numbers)
        result = reducer(result, x);
    return result;
};

int main() {
    std::cout << reduce([](float x, float y) {return x/y;}, {1,2,3,4,5});
}

在 Typescript 中,我可以使用

typeof
:

const exampleReducer = (x: number, y: number) => x+y;

const reduce = (reducer: typeof exampleReducer, numbers: number[]) => {
    let result = numbers[0];
    numbers.forEach((n) => { result = reducer(result, n);})
    return result
}

console.log(reduce((x, y) => x/y, [1,2,3,4,5]))

我知道Python 3.11将在

reveal_type
模块中添加一个
typing
函数 - 已经在
typing-extensions
中可用,但文档指出:

当静态类型检查器遇到对此函数的调用时,它会发出带有参数类型的诊断信息。

所以看起来类型检查器可以推断类型,但仅用于调试目的......

是否有 Python 等效项允许使用

exampleReducer
的类型作为类型注释?

def exampleReducer(x: float, y: float): 
    return x+y;

def reduce(reducer: ???what goes here??? exampleReducer, numbers: list[float]):
    result = numbers[0];
    for n in numbers:
        result = reducer(result, n)
    return result

print(reduce(lambda x, y: x/y, [1,2,3,4,5]))
python python-typing
1个回答
0
投票

我知道的唯一方法是没有真正的功能类型,但我们有

typing.Protocol
,作为解决方法。

class exampleReducer(typing.Protocol):
    def __call__(x: float, y: float): 
        return x+y;

def reduce(reducer: exampleReducer, numbers: list[float]):
    result = numbers[0];
    for n in numbers:
        result = reducer(result, n)
    return result

print(reduce(lambda x, y: x/y, [1,2,3,4,5]))

此代码被 PyCharms 类型检查器接受,因为协议使用鸭子类型而不是继承。但我不知道这是否也适用于其他静态类型检查器。

© www.soinside.com 2019 - 2024. All rights reserved.