Detailed explanation of Higher-order Function
What is a higher-order function?
Let’s start with a small daily development scenario:
Suppose you want to write a file filtering tool:
- Initially, only images with "size ≥ 10MB" are filtered, and a special function must be written;
- Later, if I want to filter documents "created after 2023", I have to change the code;
- Later I want to filter "File names containing
_project"The code file... is too troublesome!
If you use higher-order functions to solve the problem, you only need to write a general screening framework, extract the judgment logic of "what is qualified" into a separate function, and pass it to the framework as a parameter.
Back to the definition: **Higher-order functions are a type of function that "can take other functions as parameters" or "can return other functions as results." ** It is the core concept of functional programming, which can help us change the code from "hard-coded logic" to "extracted reuse + flexible combination".
Prerequisite knowledge: "Functions are first-class citizens" in Python
The premise for playing with high-order functions in Python is: functions, like integers, strings, and lists, are "first-class citizens" and enjoy three core rights:
1. Variables can "point to" functions
2. The essence of the function name is "the variable pointing to the function"
Be extra careful about this, never modify references to built-in functions casually:
⚠️ Important reminder: In production code, never overwrite references to built-in functions and modules!
The first major feature: functions as parameters
This is our most commonly used high-order function play - extract "specific operations" into functions and pass them to "general process".
1. A simple getting started example
2. Three classic high-order parameter functions built into Python
① map(): Batch "transform" data
It uses a "transformation function" to process each element of the iterable object (list, tuple, etc.) one by one, and returns an iterator (saving memory).
② filter(): Batch "filter" data
Use a "returnTrue/False"Judgment function (predicate)", leave the elements that meet the conditions, and also return the iterator.
③ functools.reduce():Batch "aggregate" data
Need to start withfunctoolsmodule import. It will stack the elements of the iterable object one by one and finally get a result.
The second major feature: function as return value
High-order functions can not only "receive tools", but also "make tools" - returning different customized functions based on different inputs.
1. Closure: a tool to create “remember context”
A concept is introduced here - closure: If the returned internal function references the variables of the external function (even if the external function has been executed), then this internal function is called a closure.
2. Decorator: a tool for creating “adding special effects to functions”
This is the most commonly used and elegant combination of closure + higher-order function in Python! It can add common functions such as "logging, timing, and permission verification" to the function without modifying the original function code.
① The most basic decorator
Modern Python high-order function gadgets
1. functools.partial(): "Prefilled parameters" simplifies calling
If you have a function but often need to pass in certain fixed parameters, you can usepartial()Prefill them in to create a new, cleaner function.
2. Type annotation support
Python 3.5+typingModules can add standardized type annotations to high-order functions to improve readability and IDE completion experience.
Best practices for higher-order functions
- Parameter naming should be clear: If the parameters of higher-order functions are functions, try to use
op(operate),predicate(predicate/judgment),key_func(key function used for sorting) this kind of meaningful name, rather thanf、g。 - Internal logic should be simple: High-order functions are only responsible for "general processes". Do not stuff specific business logic into them, otherwise you will lose flexibility.
- Don’t modify external variables in closures: If you really want to modify them, you must use
nonlocalkeyword (Python 3+), otherwise it will be treated as a local variable of the inner function. - Be cautious in performance-sensitive scenarios: Function calls have a certain overhead, and excessive use of higher-order functions in a large number of loops may slow things down (such as using list comprehensions instead of simple
map/filterwill be faster).
Summarize
High-order functions achieve abstraction, reuse, and flexible combination of code by "treating functions as first-class citizens":
- Function as parameter: You can separate "general process" and "specific operation";
- Function as return value: You can create customized tools that "remember context" or "add special effects";
- Python built-in tools:
map、filter、functools.reduce、functools.partial, decorator.
Mastering higher-order functions is an important step from "Getting Started with Python" to "Advanced Python" and can help you write simpler, more elegant, and easier-to-maintain code!

