CodeBlanks Logo Icon CodeBlanks

Callable

Learn callable types with Callable.

Callable

Sometimes you take a function as a parameter. Callable declares the type of callable objects (functions, lambdas, classes).

The syntax is Callable[[ArgT1, ArgT2], RetT]. The first list is the parameter types, the second item is the return type.

from typing import Callable

def apply(fn: Callable[[int], int], x: int) -> int:
    return fn(x)

print(apply(lambda n: n * 2, 5))  # 10

For a parameterless function, write Callable[[], int]. The return type is always present.

Higher-order functions

Functions that take a function as a parameter or return one are called higher-order functions. map, filter and sorted are examples.

The Callable hint makes their signatures clear. Example: def map_int(fn: Callable[[int], int], items: List[int]) -> List[int]:. Here what fn does is explicit.

Nested Callables are also possible: Callable[[int], Callable[[int], int]] means a function taking an integer and returning a function.

Practice apply function with Callable

Write apply(fn: Callable[[int], int], x: int) -> int. The body contains return fn(x). Import Callable from typing. Call print(apply(lambda n: n * 2, 5)).

Starter code

main.py
# import Callable from typing
# apply(fn: Callable[[int], int], x: int) -> int: call fn with x
# print apply with lambda n: n * 2 and 5

Sample solution

main.py
from typing import Callable

def apply(fn: Callable[[int], int], x: int) -> int:
    return fn(x)

print(apply(lambda n: n * 2, 5))

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What kind of object does Callable[[int], int] accept?

  • An int value
  • A function taking int and returning int Correct answer
  • A list of ints
  • Only a class

Explanation: Callable[[int], int] is the type of a function taking an int and returning an int.

2 Import Callable

Question
from typing import ____

def apply(fn: Callable[[int], int], x: int) -> int:
    return fn(x)
Answer
from typing import Callable

def apply(fn: Callable[[int], int], x: int) -> int:
    return fn(x)

Explanation: Callable comes from typing; it declares the callable type.

3 Match the Callable parts

Term Meaning
Callable[[int], int] Takes int, returns int
Callable[[], int] No params, returns int
[int, str] Parameter types
int (second) Return type

All lessons in Advanced