Back to series
· 9 min read

Python Higher-Order Functions and Functions as Objects


I. What Does It Mean for Functions to Be Objects?

In Python, a function is not only a piece of executable code but also an object.

Ordinary variables can refer to integers, strings, lists, and dictionaries, and function names can likewise refer to function objects.

For example:

def greet():
    print("Hello Python")

print(greet)
print(type(greet))

The output is similar to:

<function greet at 0x...>
<class 'function'>

Here, greet is not a function call; it is a name that points to a function object.

Only when you call it with parentheses does the function execute:

greet()

Output:

Hello Python

1.1 Function Names and Function Objects

To understand functions as objects, you first need to distinguish between function names and function objects.

def say_hello():
    print("Hello")

another = say_hello

say_hello()
another()

Output:

Hello
Hello

Execution process:

  1. def say_hello() creates a function object.
  2. The name say_hello is bound to that function object.
  3. another = say_hello binds another name to the same function object.
  4. Both names can call this function.

You can verify that they refer to the same object:

print(say_hello is another)

Output:

True

Therefore, a function name is merely a name that refers to a function object, and a single function object can be referenced by multiple names at the same time.

1.2 Functions Can Be Assigned Like Ordinary Objects

def add(a, b):
    return a + b

operation = add

print(operation(10, 20))

Output:

30

No new function is created here; operation simply points to an existing function object.

1.3 Functions Can Be Stored in Containers

Functions can be placed in lists, tuples, and dictionaries.

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

operations = [add, subtract, multiply]

print(operations[0](10, 5))
print(operations[1](10, 5))
print(operations[2](10, 5))

Output:

15
5
50

You can also use a dictionary to map operation names to function objects:

operations = {
    "add": lambda a, b: a + b,
    "subtract": lambda a, b: a - b,
    "multiply": lambda a, b: a * b
}

print(operations["add"](10, 5))
print(operations["multiply"](10, 5))

Output:

15
50

This approach is commonly used for command dispatch, strategy selection, and dynamic invocation.

II. First-Class Object Features of Python Functions

Python treats functions as first-class objects (First-Class Objects), meaning that functions can participate in program execution like any other object.

As first-class objects, functions mainly have the following capabilities:

  1. They can be assigned to variables.
  2. They can be passed as function arguments.
  3. They can be returned as function return values.
  4. They can be stored in data structures such as lists and dictionaries.
  5. They can be dynamically created and used at runtime.

Among these, the ability to pass functions as arguments and return them as values is the foundation of higher-order functions.

2.1 Functions Can Be Assigned to Variables

def square(x):
    return x * x

calculate = square

print(calculate(5))

Output:

25

2.2 Functions Can Be Passed as Arguments

def execute(func, value):
    return func(value)

def square(x):
    return x * x

result = execute(square, 5)

print(result)

Output:

25

Here, square is not followed by parentheses, so the function object is passed, not the result of executing the function.

2.3 Functions can be used as return values

def get_operation():
    def add(a, b):
        return a + b

    return add

operation = get_operation()

print(operation(10, 20))

Output:

30

get_operation() returns the function object add, not the result of executing add().

2.4 Functions can be stored and called dynamically

def start():
    return "程序启动"

def stop():
    return "程序停止"

handlers = {
    "start": start,
    "stop": stop
}

action = "start"

print(handlers[action]())

Output:

Program started

This approach separates behavior in the program from the specific invocation logic.

III. What Is a Higher-Order Function

A higher-order function is a function that satisfies any one of the following conditions:

  • It accepts one or more functions as parameters.
  • It returns a function object as its return value.

Simply put, a higher-order function can operate on other functions, not just on ordinary data such as numbers and strings.

For example:

def execute(func, value):
    return func(value)

def double(x):
    return x * 2

result = execute(double, 10)

print(result)

Output:

20

Here:

  • double is an ordinary function.
  • execute accepts double as a parameter.
  • execute calls the passed-in function internally.
  • execute is therefore a higher-order function.

3.1 Basic Structure of Higher-Order Functions

Higher-order functions usually have two typical forms.

Form 1: Accepting a function as a parameter

def higher_order(func, value):
    return func(value)

Form 2: Returning a function object

def higher_order():
    def inner():
        return "Hello"

    return inner

Both forms reflect that functions can be passed and operated on as data.

3.2 Execution Flow of a Higher-Order Function

flowchart TD
    A["Define an ordinary function"] --> B["Create a function object"]
    B --> C["Pass the function object to a higher-order function"]
    C --> D["Higher-order function receives the function parameter"]
    D --> E["Call the function as needed"]
    E --> F["Obtain the execution result"]
    F --> G["Return the result or continue processing"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

IV. Functions as Parameters: Behavior Injection

Passing a function as a parameter means the caller can hand the specific execution logic to the called function.

This design is also called behavior injection.

4.1 Customizing Execution Behavior

def calculate(a, b, operation):
    return operation(a, b)

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

print(calculate(10, 20, add))
print(calculate(10, 20, multiply))

Output:

30
200

calculate() does not need to care whether addition or multiplication is actually performed; it only needs to call the function passed in.

This design separates two responsibilities:

  • The caller decides what operation to perform.
  • The higher-order function is responsible for organizing the execution process.

4.2 Passing Temporary Functions with Lambda

If the logic being passed is very simple, you can use a Lambda:

def calculate(a, b, operation):
    return operation(a, b)

result = calculate(10, 20, lambda x, y: x + y)

print(result)

Output:

30

Lambda is suitable for simple, short logic. If the operation contains complex business rules, it is recommended to use a regular function.

4.3 Function Parameters Can Enable Strategy Switching

Suppose a program needs to calculate discounts according to different strategies:

def normal_discount(price):
    return price * 0.9

def vip_discount(price):
    return price * 0.8

def promotion_discount(price):
    return price * 0.7

def checkout(price, discount_strategy):
    return discount_strategy(price)

print(checkout(100, normal_discount))
print(checkout(100, vip_discount))
print(checkout(100, promotion_discount))

Output:

90.0
80.0
70.0

This design can avoid piling up a large number of conditional branches inside one function.

4.4 Function Parameters and Callback Functions

A callback function (Callback) is a function passed to another function via a parameter and invoked by the receiver at a specific point.

def process_data(data, callback):
    result = data * 2
    callback(result)

def show_result(value):
    print("处理结果:", value)

process_data(10, show_result)

Output:

处理结果: 20

Here, show_result is the callback function.

The callback mechanism is commonly used in:

  • Event handling.
  • Asynchronous tasks.
  • Notification when a network request completes.
  • GUI user interaction.
  • Data processing pipelines.
  • Plugin and extension mechanisms.

Note that a callback function itself is not necessarily asynchronous. Synchronous programs can also use callbacks.

5. Functions as Return Values: Dynamically Generating Functions

Functions can not only be used as parameters, but also as the return value of another function.

This approach can dynamically create different function behaviors based on runtime conditions.

5.1 Returning an Inner Function

def get_greeting():
    def greet():
        return "Hello Python"

    return greet

func = get_greeting()

print(func())

Output:

Hello Python

get_greeting() returns an inner function object.

5.2 Returning Different Functions Based on Parameters

def get_operation(operation):
    if operation == "add":
        return lambda a, b: a + b

    if operation == "multiply":
        return lambda a, b: a * b

    raise ValueError("不支持的操作")

add = get_operation("add")
multiply = get_operation("multiply")

print(add(10, 20))
print(multiply(10, 20))

Output:

30
200

Here, the specific behavior of the function is determined by runtime parameters.

5.3 Function Factory

The process of generating functions according to different configurations can form a function factory (Function Factory).

For example:

def make_multiplier(factor):
    def multiply(value):
        return value * factor

    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
ten_times = make_multiplier(10)

print(double(5))
print(triple(5))
print(ten_times(5))

Output:

10
15
50

Each time make_multiplier() is called, a new inner function object is created, along with a corresponding outer variable binding.

Function factories can be used to:

  • Dynamically generate handlers.
  • Create validation functions with different configurations.
  • Encapsulate different computation strategies.
  • Create functions with independent state.
  • Simplify the definition of repetitive functions.

6. Functions as Objects and Their Relationship with Closures

A closure is an important application of a function's ability to act as an object.

A closure is formed when an inner function references a variable in an outer function, and the inner function can still access those variables after the outer function has finished executing.

For example:

def make_counter():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter

counter = make_counter()

print(counter())
print(counter())
print(counter())

Output:

1
2
3

Here:

  • make_counter() is the outer function.
  • counter() is the inner function.
  • count is a local variable in the outer function.
  • counter references count.
  • nonlocal allows the inner function to rebind count in the outer function.

6.1 Multiple Closure Instances Have Independent State

def make_counter():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter

counter_a = make_counter()
counter_b = make_counter()

print(counter_a())
print(counter_a())
print(counter_b())
print(counter_b())

Output:

1
2
1
2

The two closures each hold their own outer variable binding and do not affect each other.

6.2 Underlying Information of Closures

Python function objects provide several attributes that allow you to inspect closure-related information.

def outer():
    message = "Hello"

    def inner():
        return message

    return inner

func = outer()

print(func.__code__.co_freevars)
print(func.__closure__)

Example output:

('message',)
(<cell at ...: str object at ...>,)

Here:

  • __code__.co_freevars: Records the names of the free variables referenced by the function.
  • __closure__: A tuple that holds the closure cells.
  • cell_contents: Provides access to the object in a closure cell.

For example:

print(func.__closure__[0].cell_contents)

Output:

Hello

In CPython, closures usually store outer bindings through cell objects. This is an implementation detail and should not be regarded as an internal structure that all Python implementations must use.

7. Python Built-in Higher-Order Functions

The Python standard library provides many built-in functions and tools that can accept function objects.

The most common ones are map(), filter(), sorted(), max(), and min().

7.1 map: Mapping Transformation

map() applies the specified function to the elements of one or more iterables.

Syntax:

map(function, iterable, ...)

Example:

numbers = [1, 2, 3, 4, 5]

result = map(lambda x: x * 2, numbers)

print(list(result))

Output:

[2, 4, 6, 8, 10]

map() returns an iterator and does not immediately generate a complete list.

It can also process multiple iterables at the same time:

a = [1, 2, 3]
b = [10, 20, 30]

result = map(lambda x, y: x + y, a, b)

print(list(result))

Output:

[11, 22, 33]

By default, map() stops at the shortest iterable.

7.2 filter: Filtering by condition

filter() filters elements based on the truth value of the result returned by the function.

Syntax:

filter(function, iterable)

Example:

numbers = [1, 2, 3, 4, 5, 6]

result = filter(lambda x: x % 2 == 0, numbers)

print(list(result))

Output:

[2, 4, 6]

If the function argument is None, filter() filters directly based on the truth value of the elements themselves:

values = [0, 1, "", "Python", None, [], [1, 2]]

print(list(filter(None, values)))

Output:

[1, 'Python', [1, 2]]

7.3 sorted: Custom sorting

sorted() can accept a function through the key parameter to generate the sorting key.

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Tom", "score": 78}
]

result = sorted(
    students,
    key=lambda student: student["score"],
    reverse=True
)

print(result)

Output:

[
    {'name': 'Bob', 'score': 92},
    {'name': 'Alice', 'score': 85},
    {'name': 'Tom', 'score': 78}
]

The key function is responsible for extracting the sorting criterion, while the actual sorting is done by sorted().

7.4 max and min: Custom comparison basis

products = [
    {"name": "Laptop", "price": 5000},
    {"name": "Phone", "price": 3000},
    {"name": "Tablet", "price": 2000}
]

most_expensive = max(products, key=lambda item: item["price"])
cheapest = min(products, key=lambda item: item["price"])

print(most_expensive)
print(cheapest)

Output:

{'name': 'Laptop', 'price': 5000}
{'name': 'Tablet', 'price': 2000}

7.5 reduce: Accumulation

reduce() is in the functools module and can use a binary function to progressively combine the elements in an iterable.

from functools import reduce

numbers = [1, 2, 3, 4, 5]

result = reduce(lambda x, y: x + y, numbers)

print(result)

Output:

15

Calculation process:

1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15

Specifying an initial value:

result = reduce(
    lambda x, y: x + y,
    [1, 2, 3],
    10
)

print(result)

Output:

16

For simple summation, using sum() directly is usually clearer; reduce() is better suited to scenarios that require custom accumulation rules.

VIII. Higher-Order Functions and Functional Programming

Functions as objects and higher-order functions are an important foundation for Python's support of functional programming.

Functional Programming emphasizes using functions to organize program logic and completing computations through function composition and data transformation.

Python is not a purely functional language, but rather a language that supports multiple programming paradigms.

8.1 Pure Functions

A Pure Function has two important characteristics:

  1. Always produce the same output for the same input.
  2. Produce no observable external side effects.

For example:

def add(a, b):
    return a + b

For the same a and b, the result is always the same, and no external state is modified.

In contrast:

total = 0

def add_to_total(value):
    global total
    total += value
    return total

This function modifies external state, so it is not a pure function.

Pure functions are easier to test, reuse, and compose, but not all business logic is suited to being forced into a pure-function design.

8.2 Function Composition

Function composition is the practice of using the output of one function as the input of another.

For example:

def add_one(x):
    return x + 1

def double(x):
    return x * 2

result = double(add_one(5))

print(result)

Output:

12

The calculation process:

5 → add_one → 6 → double → 12

You can define a general-purpose composition function:

def compose(f, g):
    return lambda x: f(g(x))

add_one = lambda x: x + 1
double = lambda x: x * 2

combined = compose(double, add_one)

print(combined(5))

Output:

12