python - 函数的类型注释,返回一个采用 args 和 kwargs 的函数
问题描述
以下示例代码在运行时工作,但不被接受mypy --strict
:
from typing import Any, Callable, TypeVar
TypeT = TypeVar('TypeT')
def log_call(msg: str) -> Callable[..., TypeT]:
def do_call(func: Callable[..., TypeT], *args: Any, **kwargs: Any) -> TypeT:
print(msg)
return func(*args, **kwargs)
return do_call
def double(val: int) -> int:
return 2 * val
def plus(a: int, b: int) -> int:
return a + b
def plus_plus(a: int, b: int, c: int) -> int:
return a + b + c
result_1 = log_call('hi')(double, 1)
result_2 = log_call('hi')(plus, 2, 3)
result_3 = log_call('hi')(plus_plus, 2, 3, 4)
result_4 = log_call('hi')(double, val=1)
print(result_1)
print(result_2)
print(result_3)
print(result_4)
mypy
输出:
test.py:26: error: Need type annotation for 'result_1'
test.py:27: error: Need type annotation for 'result_2'
test.py:28: error: Need type annotation for 'result_3'
test.py:30: error: Need type annotation for 'result_4'
test.py:32: error: Cannot determine type of 'result_1'
test.py:33: error: Cannot determine type of 'result_2'
test.py:34: error: Cannot determine type of 'result_3'
test.py:35: error: Cannot determine type of 'result_4'
现在result*
我不想给变量添加类型注释,我想调整函数的类型注释,这样就可以推导出其他的了。这是我的尝试:
from typing import Any, Callable, TypeVar
TypeT = TypeVar('TypeT')
def log_call(msg: str) -> Callable[[Callable[..., TypeT], Any, Any], TypeT]:
def do_call(func: Callable[..., TypeT], *args: Any, **kwargs: Any) -> TypeT:
print(msg)
return func(*args, **kwargs)
return do_call
def double(val: int) -> int:
return 2 * val
def plus(a: int, b: int) -> int:
return a + b
def plus_plus(a: int, b: int, c: int) -> int:
return a + b + c
result_1 = log_call('hi')(double, 1)
result_2 = log_call('hi')(plus, 2, 3)
result_3 = log_call('hi')(plus_plus, 2, 3, 4)
result_4 = log_call('hi')(double, val=1)
print(result_1)
print(result_2)
print(result_3)
print(result_4)
但是现在参数的数量不再适合:
test.py:26: error: Too few arguments
test.py:28: error: Too many arguments
test.py:30: error: Unexpected keyword argument "val"
我想我正在寻找类似的东西
def log_call(msg: str) -> Callable[[Callable[..., TypeT], ...], TypeT]:
但是这种语法是不合法的。
有没有办法解决这个问题?
解决方案
推荐阅读
- bash - 在文件名中使用 ^M 删除或符号链接
- c# - 如何在 Nuke 构建中获取项目的 OutputPath
- powerbi - 刷新错误提示 Power BI 中的内存不足
- gradle - Process 'command 'C:\Program Files\Java\jdk\bin\java.exe'' 以非零退出值 1 eclipse 结束
- c# - 在gridview中设置文本框的值
- javascript - 识别多个脚本的公共变量
- visual-studio-code - 空手道,VScode:“运行空手道测试”codelens 未显示
- ios - iOS 中 varispeed 与 RemoteIO 的连接
- c# - 如何在 linux ubuntu 服务器(18.06)中执行 .exe 文件
- java - 我如何将文件读取为字节然后在java(android)中将其编码为base64