🧠 Python Higher-Order Functions — Functions That Work With Functions

Introduction 🌟

A Higher-Order Function (HOF) is any function that does at least one of the following:

  • ✔ Takes another function as an argument
  • ✔ Returns a function
  • ✔ Or does both!

HOFs enable functional programming in Python — making code more reusable, expressive, and elegant.

Note

💡 Examples of built-in HOFs: map(), filter(), reduce(), sorted() with key functions.

1. Basic Example of Higher-Order Function 🧱

hof_basic.py

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

def add_one(x):
    return x + 1

print(apply_twice(add_one, 5))  # 7

✔ Function takes another function as argument.

2. Returning Functions (Function Factory) 🏭

return_function.py

def power(n):
    def calc(x):
        return x ** n
    return calc

square = power(2)
cube = power(3)

print(square(4))  # 16
print(cube(3))    # 27

Note

✔ HOF returns a function → closures in action.

3. Using Built-In Higher-Order Functions 🔧

map()

map_hof.py

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)

filter()

filter_hof.py

evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)

reduce()

reduce_hof.py

from functools import reduce

total = reduce(lambda a, b: a + b, nums)
print(total)

4. Using Functions as Arguments 🎯

function_as_argument.py

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

def double(n):
    return n * 2

print(execute(double, 10))

5. Using Functions as Return Values 🔄

returning_function.py

def greeting(language):
    if language == "en":
        return lambda name: f"Hello {name}"
    else:
        return lambda name: f"வணக்கம் {name}"

greet = greeting("en")
print(greet("Sathish"))

✔ Useful for factory patterns and dynamic behavior.

6. Higher-Order Functions + Closures 🔗

hof_closure.py

def multiplier(n):
    def mul(x):
        return x * n
    return mul

times3 = multiplier(3)
print(times3(10))  # 30

7. Higher-Order Functions in Decorators 🎀

Decorators are the best real-world example of higher-order functions.

hof_decorator.py

def log(func):
    def wrapper():
        print("Calling", func.__name__)
        return func()
    return wrapper

@log
def hello():
    print("Hello")

hello()

8. Higher-Order Functions for Sorting 🔽

sorted() accepts a function as key.

hof_sorted.py

names = ["Sathish", "Kumar", "Arun"]

sorted_names = sorted(names, key=lambda x: len(x))
print(sorted_names)

9. Higher-Order Functions for Validation ✔️

hof_validation.py

def validator(condition):
    def check(value):
        return condition(value)
    return check

is_even = validator(lambda x: x % 2 == 0)
print(is_even(4))   # True

10. Combining HOFs for Elegant Pipelines 🔧

hof_pipeline.py

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

result = list(
    filter(lambda x: x > 5,
        map(lambda x: x * x,
            filter(lambda x: x % 2 == 1, data)
        )
    )
)

print(result)

Note

✔ Square odd numbers → filter values above 5
✔ Functional programming style

11. Real-World Applications 🌍

🔹 Logging

realworld_logging.py

def logger(func):
    def wrapper(*args):
        print("Running:", func.__name__)
        return func(*args)
    return wrapper

🔹 Authentication

realworld_auth.py

def allow(role):
    def decorator(func):
        def wrapper(user):
            if user != role:
                return "Access Denied"
            return func(user)
        return wrapper
    return decorator

🔹 Retry Mechanism

realworld_retry.py

def retry(times):
    def decorator(func):
        def wrapper():
            for _ in range(times):
                result = func()
                if result:
                    return result
            return "Failed after retries"
        return wrapper
    return decorator

Conclusion 🎉

>>“Higher-order functions make Python expressive, dynamic, and powerful — enabling elegant patterns like decorators, closures, and functional pipelines.” ✨

You now clearly understand Higher-Order Functions! Want the next topic? Try Modules, Decorators with Parameters, OOP, or Pure Functions. Just tell me! 😊