Fundamentals 6 min read

Returning Functions in Python: Simple Functions, Closures, Decorators, and More

This article explains how Python functions can be returned as values, covering simple functions, stateful closures, multiple returns, closures, decorators, function factories, anonymous lambda functions, and class methods, each illustrated with clear code examples and explanations.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Returning Functions in Python: Simple Functions, Closures, Decorators, and More

Introduction

In Python, functions can be passed as arguments and also returned as values, enabling flexible and powerful programming patterns.

1. Returning a Simple Function

def create_adder(n):
    def adder(x):
        return x + n
    return adder
add_five = create_adder(5)
print(add_five(3))  # 输出:8

The create_adder function returns an adder function that adds the captured n to its input.

2. Returning a Stateful Function (Closure)

def create_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment
counter = create_counter()
print(counter())  # 输出:1
print(counter())  # 输出:2
print(counter())  # 输出:3

The inner increment function retains and updates the count variable each time it is called.

3. Returning Multiple Functions

def create_math_functions():
    def add(x, y):
        return x + y
    def subtract(x, y):
        return x - y
    return add, subtract
math_functions = create_math_functions()
add_func, subtract_func = math_functions
print(add_func(5, 3))  # 输出:8
print(subtract_func(5, 3))  # 输出:2

This example shows a function that returns two related functions.

4. Returning a Closure

def create_multiplier(factor):
    def multiplier(x):
        return x * factor
    return multiplier
multiply_by_two = create_multiplier(2)
multiply_by_three = create_multiplier(3)
print(multiply_by_two(5))  # 输出:10
print(multiply_by_three(5))  # 输出:15

The returned multiplier can access the factor from its defining scope.

5. Returning a Decorator

def create_decorator(prefix):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(f"{prefix}: Calling {func.__name__}")
            result = func(*args, **kwargs)
            print(f"{prefix}: Called {func.__name__}")
            return result
        return wrapper
    return decorator
log_decorator = create_decorator("LOG")
@log_decorator
def say_hello(name):
    print(f"Hello, {name}!")
say_hello("Alice")

The decorator adds logging before and after the wrapped function execution.

6. Returning a Function Factory

def create_function_factory(base):
    def create_function(factor):
        def func(x):
            return x * factor + base
        return func
    return create_function
function_factory = create_function_factory(10)
multiply_by_two = function_factory(2)
multiply_by_three = function_factory(3)
print(multiply_by_two(5))  # 输出:20
print(multiply_by_three(5))  # 输出:25

The factory produces functions that incorporate both a base value and a factor.

7. Returning an Anonymous (Lambda) Function

def create_anonymous_function(factor):
    return lambda x: x * factor
multiply_by_two = create_anonymous_function(2)
multiply_by_three = create_anonymous_function(3)
print(multiply_by_two(5))  # 输出:10
print(multiply_by_three(5))  # 输出:15

This returns a concise lambda expression that multiplies its input.

8. Returning Class Methods

class MathOperations:
    @staticmethod
    def add(x, y):
        return x + y
    @staticmethod
    def subtract(x, y):
        return x - y

def create_math_methods():
    return MathOperations.add, MathOperations.subtract
math_methods = create_math_methods()
add_func, subtract_func = math_methods
print(add_func(5, 3))  # 输出:8
print(subtract_func(5, 3))  # 输出:2

The function returns static methods from a class, allowing them to be used as regular functions.

9. Summary

The article demonstrated various ways to return functions in Python, including simple functions, stateful closures, multiple returns, closures accessing outer variables, decorators, function factories, anonymous lambda functions, and class methods.

pythonprogramming fundamentalsFunctionsdecoratorsHigher-order FunctionsClosures
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.