partial and reduce
Make a third partial, for example ten_times = partial(power, 10), and predict ten_times(3).
functools holds tools that build new functions from old ones: partial fixes some arguments, reduce folds a sequence into one value, lru_cache and cache remember results, cached_property computes an attribute once, singledispatch picks code by type, and wraps keeps a wrapper honest.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use partial to make to_binary from int so that to_binary("101") returns 5. (Hint: int(text, base=2).)
Use reduce to multiply [1, 2, 3, 4, 5] together (the factorial of 5), starting from 1.
Write slow_square(n) with @lru_cache(maxsize=2) that records each real call in a list. Call it with 1, 2, 1, 3, 1 in that order, then print the list and slow_square.cache_info(). Predict first which value gets evicted when 3 arrives.
Explain it without notes
What does functools.partial do and when is it useful?
How does lru_cache work, what are its requirements, and what can go wrong?
When would you use cached_property instead of lru_cache?
Why does reduce need an initial value, and when would you avoid reduce completely?
What does singledispatch do, how does it choose an implementation, and what are its limits?
Expected output
square(5): 25
cube(2): 8
partial remembers: power {'exponent': 2}
reduce sum: 10
reduce longest: bbbb
reduce empty with start: 0