K.Mulier
K.Mulier

Reputation: 9620

How annotate a function that takes another function as parameter?

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( )?

Upvotes: 36

Views: 16311

Answers (2)

Alex
Alex

Reputation: 19104

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)

Upvotes: 44

Karl
Karl

Reputation: 5822

Shouldn't it just be function?

>>> type(func_a)
function

Upvotes: 0

Related Questions