How annotate a function that takes another function as parameter?

Viewed 6011

I'm experimenting with type annotations in Python. Most cases are pretty clear, except for those functions that take another function as parameter.

Consider the following example:

from __future__ import annotations

def func_a(p:int) -> int:
    return p*5
    
def func_b(func) -> int: # How annotate this?
    return func(3)
    
if __name__ == "__main__":
    print(func_b(func_a))

The output simply prints 15.

How should I annotate the func parameter in func_b( )?

2 Answers

You can use the typing module for Callable annotations.

The Callable annotation is supplied a list of argument types and a return type:

from typing import Callable

def func_b(func: Callable[[int], int]) -> int:
    return func(3)

Shouldn't it just be function?

>>> type(func_a)
function
Related