0% found this document useful (0 votes)
2 views

Python_Iterators_Generators_Decorators_CheatSheet_Clean

This cheat sheet provides an overview of Python iterators, generators, and decorators, including their definitions, use cases, and examples. It highlights best practices for implementing these concepts and includes ready-to-use code snippets for infinite generators and retry decorators. The document serves as a quick reference for enhancing Python programming skills in these areas.

Uploaded by

arijitrajiv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python_Iterators_Generators_Decorators_CheatSheet_Clean

This cheat sheet provides an overview of Python iterators, generators, and decorators, including their definitions, use cases, and examples. It highlights best practices for implementing these concepts and includes ready-to-use code snippets for infinite generators and retry decorators. The document serves as a quick reference for enhancing Python programming skills in these areas.

Uploaded by

arijitrajiv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python Iterators, Generators & Decorators - Expert Cheat Sheet

Complete Expert Cheat Sheet

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

for i in CountUpTo(3): print(i)

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

for num in count_up_to(3): print(num)


Python Iterators, Generators & Decorators - Expert Cheat Sheet

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")

With functools.wraps (Best Practice):


from functools import wraps
def log_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
Python Iterators, Generators & Decorators - Expert Cheat Sheet
return func(*args, **kwargs)
return wrapper

Industrial Use Cases


--------------------------
- Read files line-by-line (Generator)
- Paginated API fetch (Iterator)
- Function logging (Decorator)
- Retry logic (Decorator)
- Data pipelines (Generator)

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

You might also like