Advanced Function Techniques
Higher-Order Functions
Higher-order functions are functions that can take other functions as arguments or return functions as results.
graph TD
A[Higher-Order Functions] --> B[Accept Functions as Arguments]
A --> C[Return Functions]
A --> D[Transform Functions]
Map Function Example
def celsius_to_fahrenheit(temp):
return (temp * 9/5) + 32
temperatures = [0, 10, 20, 30]
fahrenheit_temps = list(map(celsius_to_fahrenheit, temperatures))
print(fahrenheit_temps) ## Output: [32.0, 50.0, 68.0, 86.0]
Closures and Function Factories
def create_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) ## Output: 10
print(triple(5)) ## Output: 15
Decorators
Decorators allow modifying or enhancing functions without changing their source code.
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def add(a, b):
return a + b
result = add(3, 4)
## Output:
## Calling add
## 7
Function Techniques Comparison
Technique |
Purpose |
Key Characteristic |
Higher-Order Functions |
Manipulate functions |
Accept/return functions |
Closures |
Create function factories |
Preserve external scope |
Decorators |
Modify function behavior |
Wrap existing functions |
Advanced Functional Programming Concepts
Partial Functions
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(4)) ## Output: 16
print(cube(3)) ## Output: 27
LabEx Practical Insights
- Advanced function techniques enable more flexible code
- Functional programming principles can simplify complex logic
- Understanding these techniques improves code modularity and reusability
By mastering these advanced function techniques, Python developers can write more elegant, efficient, and maintainable code.