Practice: functools

« Read the chapter

Q1. Product of a list

BeginnerCoding

Use reduce to print the product of [1, 2, 3, 4, 5].

Goal: Use reduce.

Q2. Longest word

IntermediateCoding

Use reduce to find the longest word in ['sun', 'planet', 'moon'] and print it.

Goal: Use reduce.

Q3. Double function

BeginnerCoding

Use partial with the function multiply(a, b) to make double, and print double(21).

Goal: Use partial.

Q4. Cache a square

IntermediateCoding

Write a cached function square(n) and call it twice with 4. Print the hit count from cache_info().

Goal: Use lru_cache.

Q5. Decorator with wraps

IntermediateCoding

Write a decorator twice that calls a function twice, using wraps. Decorate hello() that prints 'hi' and print hello.__name__ after calling it.

Goal: Use wraps.

Q6. Reduce with initial

BeginnerOutput

What does this print?

Code
from functools import reduce
print(reduce(lambda a, b: a + b, [1, 2, 3], 100))

Goal: reduce initial.

Q7. partial keyword

IntermediateOutput

What does this print?

Code
from functools import partial

def greet(greeting, name):
    return f'{greeting}, {name}!'

hi = partial(greet, 'Hi')
print(hi('Ana'))

Goal: partial positional.

Q8. Cache calls

IntermediateOutput

What does this print?

Code
from functools import lru_cache

@lru_cache(maxsize=None)
def f(x):
    print('working')
    return x + 1

print(f(1))
print(f(1))

Goal: Cache behaviour.

Q9. Name without wraps

IntermediateOutput

What does this print?

Code
def deco(func):
    def wrapper():
        return func()
    return wrapper

@deco
def task():
    return 1

print(task.__name__)

Goal: wraps purpose.

Q10. singledispatch

AdvancedOutput

What does this print?

Code
from functools import singledispatch

@singledispatch
def kind(x):
    return 'other'

@kind.register(str)
def _(x):
    return 'text'

print(kind('a'), kind(3))

Goal: singledispatch.

Q11. Sorting with cmp_to_key

AdvancedOutput

What does this print?

Code
from functools import cmp_to_key

def compare(a, b):
    return b - a

print(sorted([3, 1, 2], key=cmp_to_key(compare)))

Goal: cmp_to_key.

Q12. Fix the decorator

IntermediateDebugging

This decorator hides the real name and docstring. Fix it so print(add.__name__) shows add.

Code
def log(func):
    def wrapper(*a, **k):
        return func(*a, **k)
    return wrapper

@log
def add(a, b):
    return a + b

print(add.__name__)

Goal: Use wraps.

Q13. Fix the unhashable cache

AdvancedDebugging

This cached function fails when given a list. Fix it by passing a tuple.

Code
from functools import lru_cache

@lru_cache(maxsize=None)
def total(items):
    return sum(items)

print(total([1, 2, 3]))

Goal: Hashable arguments.

Q14. Why reduce initial

BeginnerConceptual

Why is it safer to give reduce an initial value?

Goal: reduce safety.

Q15. When not to cache

IntermediateConceptual

Name one kind of function that you should not decorate with lru_cache.

Goal: Pure functions.

Q16. Price with tax

IntermediateApplication

Use partial to make add_tax from price_with(rate, price) with rate 0.1. Print add_tax(200) as a number with one decimal.

Goal: Use partial in real tasks.

Q17. Merge dictionaries

AdvancedApplication

Use reduce to merge [{'a': 1}, {'b': 2}, {'a': 3}] into one dict and print it.

Goal: Use reduce to merge.