Higher-Order Patterns
In Python, functions are treated as first-class citizens. This means you can pass them around as arguments to other functions, return them from functions, and compose them to build incredibly expressive, clean APIs.
Let us explore these powerful higher-order programming patterns!
First-Class Functions
Because functions are first-class, you can assign them to variables or pass them into other functions like ordinary data:
Example
Output:
Passing Callbacks
You can pass a function as an argument (a “callback”) to execute it inside another function:
Example
Output:
Lambdas provide simple, inline anonymous functions, but they are limited to a single expression. For complex or multi-line logic, always use the standard def keyword.
Returning Functions
Just like passing functions, a function can create and return another function. This is often used to build customized functions:
Example
Output:
Decorators
Decorators are a beautiful Python feature that allows you to wrap a function inside another function to add additional behavior without changing the original code.
Always preserve function metadata (like names and docstrings) on decorated functions by using @wraps from Python’s standard functools module:
Example
Output:
Partial Functions
Python’s functools.partial lets you “pre-fill” some arguments of a function to create a new, specialized function:
Example
Output:
Sending email to: team@pythonforall.comSending email to: support@pythonforall.com
Function Composition
You can combine multiple small, focused functions together to build a processing pipeline:
Example
Output:
Functional Utilities
Python provides several built-in functions for functional programming style:
map: Applies a function to all items in an iterable.filter: Filters items in an iterable keeping only those where the function returnsTrue.reduce: Combines all items in an iterable into a single value.
Let us see all three in action:
Example
Output:
Mapped (Doubled): [2, 4, 6, 8]Filtered (Evens): [2, 4]Reduced (Product): 24
Higher-Order Practice
Write a decorator that prints the execution duration of any decorated function before returning its result:
PygroundTry It Out
Create a decorator that times a function and prints the duration before returning the result.
Expected Output:
crunch took 0.000s 332833500