pythonpython-typing

How to type hinte higher-order functions in python 3.6?


In the following code:

def b(i: int) -> int:
    return i

def a(i: int, b: ?) -> int:
    return i + b(i)

print(a(1, b))

How do we type hinting the function b: ? that is a parameter of a? Thank you.


Solution

  • Use the typing.Callable generic to indicate you expect a function that takes a single integer argument, returning an integer:

    from typing import Callable
    
    def a(i: int, b: Callable[[int], int]) -> int:
        return i + b(i)
    

    Callable[...] takes two arguments, the first a list of argument types, the second the return type.