First-Class Functions, functools.partial & Higher-Order Functions
1Concept
Functions in Python are first-class objects: they can be assigned to variables, stored in data structures, passed as parameters, and returned from functions. `functools.partial` pre-fills function arguments, returning a new callable with a simpler signature.
2Architecture Diagram
Original Function: calculate_cost(rate, hours, tax_rate) Partial Function: ca_cost = partial(calculate_cost, tax_rate=0.0825)
3Code Example
Python 3.12
from functools import partial
def multiply(a: int, b: int) -> int:
return a * b
double = partial(multiply, 2)
triple = partial(multiply, 3)
print(f"Double 21: {double(21)}")
print(f"Triple 10: {triple(10)}")4Expected Output
Double 21: 42 Triple 10: 30
5Key Takeaways
- ✓`partial` creates a `functools.partial` object that behaves like the original function.
- ✓Higher-order functions accept or return functions (e.g. `map`, `filter`, `sorted`).
- ✓Use `partial` to adapt callback signatures for GUI or async event handlers.