qou*_*ify 6 python type-hinting mypy python-typing
我有很多具有相同签名的函数,比如(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:'
...
Run Code Online (Sandbox Code Playgroud)
运行 mypy 结果:
file.py:4: error: Name "f" already defined on line 3
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
也许有更优雅的解决方案。不推荐,但您可以设置<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)=}")
Run Code Online (Sandbox Code Playgroud)
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'>}
Run Code Online (Sandbox Code Playgroud)