Create a singledispatch Formatter
Advanced · Write the code · from Python functools: lru_cache, partial, reduce, singledispatch
From the lesson: Python functools: lru_cache, partial, reduce, singledispatch
Imagine your functions could remember past answers, come pre-loaded with some arguments, or automatically handle different data types. That's what the functools module gives you: power-ups for your functions.
Read the lessonCreate a format_value function using @singledispatch. The base function should print Value: <value>. Register a version for int that prints Integer: <value> and one for list that prints List with <len> items. Call it with 42, [1, 2, 3], and 'hello'.
from functools import singledispatch
# Create format_value with singledispatch
# Register for int and list
# Call with 42, [1, 2, 3], and 'hello'
More functools exercises
- Cache a Factorial FunctionIntermediate
- Create a Percentage Calculator with partialIntermediate
- Reduce a List to Find the MaximumIntermediate
- Predict the partial OutputBeginner
- Build a String with reduceAdvanced
- Fix the Caching BugAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz