首页 > 解决方案 > 键入一个可调用的函数

问题描述

我有很多具有相同签名的函数,比如说(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)

标签: pythontype-hintingmypypython-typing

解决方案


也许有一个更优雅的解决方案。不推荐,但您可以设置<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'>}

推荐阅读