python - 键入一个可调用的函数
问题描述
我有很多具有相同签名的函数,比如说(int, int) -> int
.
有没有办法用 a Callable
(或其他东西)键入这些函数,以避免为每个函数指定参数的类型和返回类型?我想做这样的事情(但显然失败了):
from typing import Callable
f: Callable[[int, int], int]
def f(x, y): # with the previous line, this is equivalent to 'def f(x: int, y: int) -> int:'
...
运行 mypy 会导致:
file.py:4: error: Name "f" already defined on line 3
Found 1 error in 1 file (checked 1 source file)
解决方案
也许有一个更优雅的解决方案。不推荐,但您可以设置<function>.__annotations__
. 更多关于它的信息在这里。
from typing import get_type_hints
callable_int_annotations = {"x": int, "y": int, "return": int}
def f_with_hint(x: int, y: int) -> int:
return x + y
def f_without_hint(x, y):
return x + y
print(f"Before {get_type_hints(f_with_hint)=}")
print(f"Before {get_type_hints(f_without_hint)=}")
f_without_hint.__annotations__ = callable_int_annotations
print(f"After {get_type_hints(f_with_hint)=}")
print(f"After {get_type_hints(f_without_hint)=}")
Before get_type_hints(f_with_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
Before get_type_hints(f_without_hint)={}
After get_type_hints(f_with_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
After get_type_hints(f_without_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
推荐阅读
- laravel - 如何使用 laravel 查询查找可用日期?
- javascript - 未处理的拒绝(TypeError):this.setState 不是函数
- swift - 如何使用 SwiftUI 获取 ScrollView 的动态文本高度
- java - Spring JPA 我可以将 pojo 传递给存储过程吗?
- apache-kafka - 如何将状态目录添加到嵌入式 Kafka 流?
- elasticsearch - 我在 kibana 网络客户端中找不到索引
- java - Java:引用 JSON 中的键值
- python - 根据分组标准偏差检查单个记录
- angular - 如何从子组件 n Angular 将 FormGroup 对象作为输出发送到父组件
- mysql - 将子查询放入偏移子句