Function Advanced Usage
Lambda Functions
Lambda functions are small, anonymous functions defined in a single line:
## Traditional function
def square(x):
return x ** 2
## Equivalent lambda function
square_lambda = lambda x: x ** 2
print(square(4)) ## Output: 16
print(square_lambda(4)) ## Output: 16
Functional Programming Techniques
graph TD
A[Functional Programming] --> B[Map]
A --> C[Filter]
A --> D[Reduce]
Map Function
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) ## Output: [1, 4, 9, 16, 25]
Filter Function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
Decorators
Decorators modify or enhance functions:
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Function took {end - start} seconds")
return result
return wrapper
@timer_decorator
def slow_function():
import time
time.sleep(2)
print("LabEx performance test")
slow_function()
Recursive Functions
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) ## Output: 120
Function Annotations
def greet(name: str, age: int) -> str:
return f"Hello {name}, you are {age} years old"
print(greet.__annotations__)
Advanced Function Techniques
Technique |
Description |
Example |
Closures |
Functions that remember environment |
def outer(x): return lambda y: x + y |
Generators |
Memory-efficient iterators |
def count_up(n): yield from range(n) |
Partial Functions |
Create new functions with preset arguments |
from functools import partial |
Error Handling in Functions
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError:
return "Invalid input type"
print(divide(10, 2)) ## Output: 5.0
print(divide(10, 0)) ## Output: Cannot divide by zero
Best Practices
- Use decorators for cross-cutting concerns
- Keep functions pure and predictable
- Use type hints for clarity
- Handle potential exceptions
Key Takeaways
- Python offers powerful functional programming features
- Decorators can modify function behavior
- Lambda functions provide concise, one-line function definitions
- Advanced techniques improve code flexibility and readability