Is there a way to declare the signature of a function object with Python (3.5+) type hints? Specifically, is there a way to declare what type of function object a function can accept or a variable can reference.
I'm sure it could get quite messy (as it can with C++11 lambda types for example), but is there at least some way to check function types?
For example:
def func1(x: int) -> int:
return x
def func2(x: int, y: int) -> int:
return x + y
# 'TwoArgFn' is a 'function type' that accepts two ints and returns an int
def takes_two(f: TwoArgFn) -> int:
return f(123, 456)
Passing func1
as an argument to takes_two
should be an error, whereas passing func2
is fine.
Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.
You can add type hints to function/method parameters and return types (Python 3.5), and variables used in assignment (effectively declarations – Python 3.6).
Using signature() function We can get function Signature with the help of signature() Function. It takes callable as a parameter and returns the annotation. It raises a value Error if no signature is provided. If the Invalid type object is given then it throws a Type Error.
For that purpose, use the typing.Callable
type (see here):
from typing import Callable
def takes_two(f: Callable[[int, int], int]) -> int:
return f(123, 456)
The first argument to Callable
is a list of types for the arguments of the function, while the second argument is the return type.
Of course, python itself does not check types at all. For this, you should use additional tools such as mypy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With