Is there a way in python's type hinting to say "function with the same signature as this one"?
The following works, but writing out the signature an extra time is required:
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)
ie I want to write something like:
def do_something(cb: Callable[callme]):
or
def do_something(cb: callme):
But neither seems to be valid. (python 3.6.3, mypy 0.570)
First, you can retrieve structured data about the signature of the function from __annotations__
:
def callme(a: int) -> bool:
return a > 1
print(callme.__annotations__)
# prints {'a': <class 'int'>, 'return': <class 'bool'>}
From here, you could work on a function that will convert it to the type as you want.
Update: a crude and probably not universal way to do just that:
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]'
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments