gpt4 book ai didi

带有kwargs的函数的python类型签名(typing.Callable)

转载 作者:行者123 更新时间:2023-12-04 19:25:45 30 4
gpt4 key购买 nike

我大量使用来自 python 3 的 python 类型支持。

最近我试图将一个函数作为参数传递,但我没有找到使用 kwargs 的任何帮助。在 typing.Callable签名。

请检查下面的代码和评论。

import typing

# some function with singnature typing
def fn1_as_arg_with_kwargs(a: int, b: float) -> float:
return a + b

# some function with singnature typing
def fn2_as_arg_with_kwargs(a: int, b: float) -> float:
return a * b

# function that get callables as arg
# this works with typing
def function_executor(
a: int,
b: float,
fn: typing.Callable[[int, float], float]):
return fn(a, b)

# But what if I want to name my kwargs
# (something like below which does not work)
# ... this will help me more complex scenarios
# ... or am I expecting a lot from python3 ;)
def function_executor(
a: int,
b: float,
fn: typing.Callable[["a": int, "b": float], float]):
return fn(a=a, b=b)

最佳答案

您可能正在寻找 Callback protocols .

简而言之,当您想表达一个带有复杂签名的可调用对象时,您要做的是创建一个自定义协议(protocol),该协议(protocol)定义了 __call__具有您想要的精确签名的方法。

例如,在您的情况下:

from typing import Protocol

# Or, if you want to support Python 3.7 and below, install the typing_extensions
# module via pip and do the below:
from typing_extensions import Protocol

class MyCallable(Protocol):
def __call__(self, a: int, b: float) -> float: ...

def good(a: int, b: float) -> float: ...

def bad(x: int, y: float) -> float: ...


def function_executor(a: int, b: float, fn: MyCallable) -> float:
return fn(a=a, b=b)

function_executor(1, 2.3, good) # Ok!
function_executor(1, 2.3, bad) # Errors

如果您尝试使用 mypy 对该程序进行类型检查,您将在最后一行收到以下(不可否认)错误:
Argument 3 to "function_executor" has incompatible type "Callable[[int, float], float]"; expected "MyCallable"

(回调协议(protocol)有点新,所以希望错误消息的质量会随着时间的推移而提高。)

关于带有kwargs的函数的python类型签名(typing.Callable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57837609/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com