Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 type hints for function signature

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.

like image 743
patmanpato Avatar asked Jul 04 '18 01:07

patmanpato


People also ask

How do you type a hint in Python?

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.

Does Python 3.6 support type hints?

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).

What is type signature in Python?

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.


1 Answers

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

like image 158
dseuss Avatar answered Oct 19 '22 23:10

dseuss