Type a Higher-Order Function
Intermediate · Write the code · from Python Type Hints: Add Types, Generics, and the typing Module
From the lesson: How Do You Type Functions and Callbacks?
Since functions are objects in Python, you sometimes need to annotate a parameter that expects a function. The Callable type handles this.
Read this part of the lessonWrite a function filter_by that takes a List[int] and a predicate function (Callable[[int], bool]) and returns a List[int] of items that pass the predicate.
Test it with an is_even function on [1, 2, 3, 4, 5, 6].
from typing import List, Callable
def filter_by(items, predicate):
# Add type hints and implement
pass
def is_even(n):
# Add type hints
return n % 2 == 0
result = filter_by([1, 2, 3, 4, 5, 6], is_even)
print(result)
More Type Hints exercises
- Add Type Hints to a FunctionIntermediate
- Type a Config FunctionIntermediate
- Predict the Output with Type HintsIntermediate
- Add Runtime Type CheckingIntermediate
- Type a Data Processing FunctionAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz