Sub topic 1
Python functools: partial, cache, and wraps
Prerequisites
You should know how to define and call Python functions, use keyword arguments, pass functions as values, and recognize that tuples are hashable while lists usually are not.
Pre-filling arguments with `partial`
functools.partial creates a new callable from an existing callable. It stores some arguments in advance. Calling the new callable supplies the remaining arguments.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5)) # 25The original power function accepts both base and exponent. The square callable fixes exponent at 2, so each call needs only a base.
partial works with positional and keyword arguments. It is useful when an API needs a one-argument callable but your function normally needs more arguments.
from functools import partial
basetwo = partial(int, base=2)
print(basetwo("101")) # 5Looking inside a partial object
A partial object exposes the callable and arguments it stores:
funcis the original callable.argsis the stored positional-argument tuple.keywordsis the stored keyword-argument dictionary.
print(square.func is power) # True
print(square.args) # ()
print(square.keywords) # {'exponent': 2}These attributes help with debugging and inspection. They do not mean that a partial object has the same metadata as the original function.
> callout note > Use partial for argument binding, not as a replacement for a wrapper when you need custom behavior such as logging or validation.
Decorators in a nutshell
A decorator is a callable that receives a function and returns a replacement function. The @ syntax applies it when Python defines the decorated function.
def announce(func):
def wrapper(*args, **kwargs):
print("starting")
return func(*args, **kwargs)
return wrapper
@announce
def greet(name):
return f"Hello, {name}"
print(greet("Ada"))Calling greet now calls wrapper, which then calls the original function.
The problem: decorators hide the original function
A naive wrapper has its own metadata. Therefore, greet.__name__ is "wrapper" instead of "greet", and the original docstring is lost. This can confuse debugging tools, documentation generators, and code that inspects functions.
The next step is to use functools.wraps inside the decorator. It copies important metadata and records the original function through __wrapped__.
Exercise
What does partial(power, exponent=2) store, and what argument does square(5) provide?
Show answer
It stores the keyword argument exponent=2; square(5) supplies base=5.