Decorators & GeneratorsBeginner
1Question 1 of 1
pythonHow do Decorators and Generators operate in Python?
Explanation & Concept
• Decorator: A function that takes another function as an argument, extends or alters its behavior, and returns a callable. Used for logging, authentication, and memoization. • Generator: A function containing `yield`. Instead of returning all elements at once into memory, it returns an iterator that lazily produces elements on demand, conserving RAM.
Code Example
python
import time
from functools import wraps
# Decorator to measure execution time
def timeit(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
duration = time.perf_counter() - start
print(f"{func.__name__} took {duration:.4f}s")
return result
return wrapper
# Generator producing infinite sequence lazily
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
@timeit
def calculate_fib():
gen = fibonacci()
return [next(gen) for _ in range(10)]
print(calculate_fib()) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]How It Works & Key Takeaways
Using `@wraps(func)` preserves function metadata (like `__name__` and docstrings). The `fibonacci` generator consumes virtually zero memory even for infinite streams.
Mock Test · 1 Questions · Optional
Ready for OOP Fundamentals?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions