如何引用函数的类型提示

2024-05-19 18:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在python的类型暗示中有没有一种方法可以说“函数的签名和这个相同”?你知道吗

以下工作正常,但需要额外的时间写出签名:

from typing import Callable

fn_sig = Callable[[int], bool]  # can I get rid of this?
def callme(a: int) -> bool:
    return a > 1

def do_something(cb: fn_sig):
    cb(1)

(我想写点什么):

def do_something(cb: Callable[callme]):

或者

def do_something(cb: callme):

但两者似乎都不成立。(python 3.6.3,mypy 0.570)


Tags: 方法函数from类型def时间dosomething
1条回答
网友
1楼 · 发布于 2024-05-19 18:19:28

首先,您可以从__annotations__检索有关函数签名的结构化数据:

def callme(a: int) -> bool:
    return a > 1

print(callme.__annotations__)

# prints {'a': <class 'int'>, 'return': <class 'bool'>}

从这里开始,您可以使用一个函数将其转换为所需的类型。你知道吗

更新:一个粗糙的,可能不是普遍的方法来做到这一点:

import typing
from typing import Callable


def callme(a: int) -> bool:
    return a > 1


def get_function_type(fn):
    annotations = typing.get_type_hints(fn)
    return_type = annotations.get('return', None)
    arg_types = []
    for k, v in annotations.items():
        if k != 'return':
            arg_types.append(v)
    return Callable[arg_types, return_type]


def example(f: get_function_type(callme)):
    pass


print(get_function_type(callme))
# prints 'typing.Callable[[int], bool]'
print(get_function_type(example))
# prints 'typing.Callable[[typing.Callable[[int], bool]], NoneType]'

相关问题 更多 >