Sub topic 2
Fixing it with `wraps`
Assume you know how to define functions, pass functions as values, use @ decorator syntax, and distinguish hashable tuples from unhashable lists.
Fixing it with `wraps`
A decorator replaces the original function with a wrapper function. A naive wrapper keeps the behavior but loses metadata such as __name__ and __doc__.
functools.wraps copies this metadata to the wrapper:
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def greet(name):
"""Return a greeting."""
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__name__) # greet
print(greet.__doc__) # Return a greeting.The wrapper still receives arbitrary positional and keyword arguments. wraps changes how the decorated function appears to tools and readers.
`update_wrapper` and `__wrapped__`
wraps(func) is a convenience decorator built on functools.update_wrapper. You can call update_wrapper directly when the wrapper already exists:
import functools
def announce(func):
def wrapper(*args, **kwargs):
print("starting")
return func(*args, **kwargs)
return functools.update_wrapper(wrapper, func)
@announce
def add(a, b):
"""Add two numbers."""
return a + b
print(add.__name__) # add
print(add.__wrapped__ is not None) # TrueThe __wrapped__ attribute points to the original function. Inspection tools can use it to look through decorator layers.
Why cache function results
Memoization means storing a function's result for a particular set of arguments. A later call with the same arguments can reuse that result instead of repeating the work.
This is safe when the function is pure: its result depends only on its arguments and it has no required side effects.
Memoizing with `cache`
functools.cache provides an unbounded memoization cache:
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
print(fib.cache_info())Arguments become cache-key components, so they must be hashable. A list argument raises TypeError; use a tuple instead. Since cache retains every entry, avoid it for functions receiving endlessly many distinct values or for results that depend on changing external state.
Exercise
What does functools.wraps preserve, and why must cached function arguments be hashable?
Show answer
It preserves metadata such as the name and docstring. Arguments must be hashable because the cache uses them to build keys.