Function as Arguments
Passing Functions as Parameters
In Python, functions are first-class objects, which means they can be passed as arguments to other functions. This powerful feature enables more flexible and dynamic programming patterns.
Basic Function Passing
def apply_operation(func, value):
return func(value)
def square(x):
return x ** 2
def double(x):
return x * 2
print(apply_operation(square, 5)) ## Output: 25
print(apply_operation(double, 5)) ## Output: 10
Common Use Cases
Sorting with Custom Key Functions
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Sort by different criteria using key functions
sorted_by_name = sorted(students, key=lambda x: x['name'])
sorted_by_grade = sorted(students, key=lambda x: x['grade'])
Functional Programming Techniques
Technique |
Description |
Example Function |
Map |
Apply function to each item |
map(func, iterable) |
Filter |
Select items based on condition |
filter(predicate, iterable) |
Reduce |
Cumulative function application |
functools.reduce(func, iterable) |
Advanced Function Passing Example
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
result = func(*args, **kwargs)
print(f"Result: {result}")
return result
return wrapper
@logger
def add(a, b):
return a + b
add(3, 4) ## Demonstrates function as argument with decorator
Function Passing Flow
graph TD
A[Original Function] -->|Passed as Argument| B[Higher-Order Function]
B -->|Executes| C[Passed Function]
C -->|Returns Result| B
B -->|Returns Final Result| D[Main Program]
Callback Functions
Callback functions are a common pattern where a function is passed as an argument to be executed later:
def process_data(data, callback):
processed = [x * 2 for x in data]
return callback(processed)
def sum_results(results):
return sum(results)
data = [1, 2, 3, 4, 5]
total = process_data(data, sum_results)
print(total) ## Output: 30
While passing functions as arguments is powerful, be mindful of performance for frequently called functions. Lambda functions and small functions have minimal overhead, but complex functions can impact performance.
Key Takeaways
- Functions can be passed as arguments in Python
- Enables flexible and dynamic programming patterns
- Useful for sorting, mapping, filtering, and creating decorators
- LabEx recommends practicing these techniques to improve coding skills