[英]How to reference the type hint of a function
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)
首先,您可以从__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]'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.