Python 3 type hints for function signature

patmanpato picture patmanpato · Jul 4, 2018 · Viewed 8.5k times · Source

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.

Answer

dseuss picture dseuss · Jul 4, 2018

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