我经常使用 Python 3 的类型支持。
最近,我尝试将函数作为参数传递,但是在 typing.Callable
签名中,我没有找到如何使用 kwargs
的帮助。
请查看以下代码和注释。
import typing
# some function with a type signature
def fn1_as_arg_with_kwargs(a: int, b: float) -> float:
return a + b
# some function with a type signature
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)
**kwargs
,它只是收集命名参数,即它取决于函数的调用方式。使用其他适当和具体的类型(例如NamedTuple、Dataclass、Enum、自定义类),也就是像通常一样明确每个参数。 - Pynchia