Fundamentals 6 min read

Using Functions as Parameters in Python: Concepts and Practical Examples

This article explains Python's higher‑order functions, showing how functions can be passed as arguments through concepts, simple examples, decorators, sorting, data processing, logging, and asynchronous callbacks, each illustrated with clear code snippets.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Functions as Parameters in Python: Concepts and Practical Examples

Python treats functions as first‑class objects, allowing them to be passed to other functions as arguments, stored in data structures, or returned from functions. This capability is known as higher‑order functions.

Basic Concept : A function can be assigned to a variable, stored, or used as a parameter, enabling flexible and modular code.

Example 1: Passing a Function as an Argument

def greet(name):
    return f"Hello, {name}!"

def process(func, arg):
    result = func(arg)
    print(result)

process(greet, "Alice")

Here greet is passed to process , which calls the function and prints the result.

Example 2: Decorator

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

The decorator my_decorator receives a function, wraps additional behavior around it, and returns the new function.

Example 3: Using a Function for Sorting

def compare_length(a, b):
    return len(a) - len(b)

words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)
# Using custom function
sorted_words_custom = sorted(words, key=compare_length)
print(sorted_words_custom)

The sorted function receives a custom key function to order items by length.

Example 4: Data Processing with a Function Parameter

def filter_even(numbers):
    return [num for num in numbers if num % 2 == 0]

def process_data(func, data):
    result = func(data)
    print(result)

numbers = [1,2,3,4,5,6,7,8,9,10]
process_data(filter_even, numbers)

The filter_even function is passed to process_data to filter a list.

Example 5: Logging Execution with a Decorator

import logging

def log_execution(func):
    def wrapper(*args, **kwargs):
        logging.info(f"Executing {func.__name__}()")
        result = func(*args, **kwargs)
        logging.info(f"Completed {func.__name__}()")
        return result
    return wrapper

@log_execution
def perform_operation():
    print("Performing an operation...")

perform_operation()

The log_execution decorator logs before and after a function runs.

Example 6: Asynchronous Callback

import asyncio

async def perform_operation(callback):
    print("Starting operation...")
    await asyncio.sleep(2)
    print("Operation completed.")
    callback()

def callback():
    print("Callback executed.")

async def main():
    await perform_operation(callback)

asyncio.run(main())

An async function receives a callback and invokes it after completing its task.

Conclusion

The article covered the fundamental idea that functions can be passed as parameters, demonstrated through simple function calls, decorators, custom sorting, data filtering, logging, and asynchronous callbacks, each with complete code examples.

Data ProcessingloggingSortingAsync CallbacksFunctions as Parameters
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.