Advanced Functions and Decorators
Duration: 8 min
Master advanced function techniques that are essential for building scalable AI applications.
Function Decorators
Decorators allow you to modify or enhance functions without changing their source code. They're widely used in AI frameworks like TensorFlow and PyTorch.
def timing_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timing_decorator
def train_model(data):
# Simulate training
import time
time.sleep(2)
return "Model trained"
train_model([1, 2, 3])train_model took 2.0023 secondsHigher-Order Functions
Functions that take other functions as arguments or return functions are powerful for creating flexible AI pipelines.
def apply_operation(func, x, y):
return func(x, y)
def add(a, b):
return a + b
def multiply(a, b):
return a * b
result1 = apply_operation(add, 5, 3)
result2 = apply_operation(multiply, 5, 3)
print(f"Add: {result1}, Multiply: {result2}")Add: 8, Multiply: 15Lambda Functions
Lambda functions are anonymous functions useful for short operations in data processing pipelines.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(f"Squared: {squared}")
# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")Squared: [1, 4, 9, 16, 25]
Evens: [2, 4]💡 Tip: Use decorators to add logging, caching, or validation to your AI model functions without modifying the core logic.
❓ What does a decorator do?