Python_Iterators_Generators_Decorators_CheatSheet_Clean
Python_Iterators_Generators_Decorators_CheatSheet_Clean
ITERATORS
-------------
Definition:
An object with __iter__() and __next__() methods.
Use Case:
- Custom data structures
- Controlled iteration
- Wrapping complex data sources
Example:
class CountUpTo:
def __init__(self, max):
self.max = max
self.current = 1
def __iter__(self):
return self
def __next__(self):
if self.current > self.max:
raise StopIteration
val = self.current
self.current += 1
return val
Best Practices:
- Raise StopIteration cleanly
- Use iter(), zip(), enumerate(), reversed()
GENERATORS
---------------
Definition:
A function that yields values instead of returning them.
Use Case:
- Stream processing
- Lazy evaluation
- Pipelines
Example:
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
Generator Expression:
squares = (x * x for x in range(5))
Best Practices:
- Use yield for memory-efficiency
- Combine with next(), for loop
- Clear documentation
DECORATORS
---------------
Definition:
Functions that modify/enhance other functions.
Use Case:
- Logging
- Authentication
- Input validation
- Caching, Timing
Basic Example:
def decorator(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
@decorator
def greet():
print("Hello")
With Arguments:
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hi(): print("Hi")
Ready-to-Use Code
--------------------------
Infinite Generator:
def infinite_counter(start=0):
while True:
yield start
start += 1
Retry Decorator:
def retry(n):
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(n):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Attempt {attempt+1} failed: {e}")
raise Exception("All retries failed")
return wrapper
return decorator