Advanced Techniques
Decorators allow dynamic modification of function behavior:
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Execution time: {time.time() - start} seconds")
return result
return wrapper
@timer_decorator
def complex_calculation(n):
return sum(range(n))
Functional Programming Techniques
Partial Functions
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, 2)
print(double(4)) ## Output: 8
Generator Functions
Memory-efficient alternative to list comprehensions:
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
gen = fibonacci_generator(5)
print(list(gen)) ## Output: [0, 1, 1, 2, 3]
Context Managers
class ResourceManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with ResourceManager() as rm:
print("Inside context")
Advanced Function Techniques
graph TD
A[Advanced Techniques] --> B[Decorators]
A --> C[Partial Functions]
A --> D[Generators]
A --> E[Context Managers]
Technique Comparison
Technique |
Use Case |
Complexity |
Performance |
Decorators |
Modify Function Behavior |
Moderate |
Efficient |
Partial Functions |
Function Specialization |
Low |
High |
Generators |
Memory Optimization |
Moderate |
Excellent |
Context Managers |
Resource Management |
Moderate |
Reliable |
Functional Programming with LabEx
Higher-Order Functions
def compose(f, g):
return lambda x: f(g(x))
def square(x):
return x ** 2
def increment(x):
return x + 1
composed_func = compose(square, increment)
print(composed_func(3)) ## Output: 16
Error Handling and Type Hints
from typing import Callable, TypeVar
T = TypeVar('T')
def safe_execute(func: Callable[..., T], *args, **kwargs) -> T:
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Error occurred: {e}")
return None
Best Practices
- Use decorators for cross-cutting concerns
- Implement generators for large datasets
- Leverage context managers for resource handling
- Utilize type hints for better code clarity
By mastering these advanced techniques, you'll write more sophisticated and elegant Python code with LabEx's professional programming approach.