pythonintermediate
Implement the Iterator Protocol
Create custom iterators using __iter__ and __next__ for lazy evaluation.
pythonPress ⌘/Ctrl + Shift + C to copy
class Countdown:
"""Custom iterator that counts down from n."""
def __init__(self, start: int):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for num in Countdown(5):
print(num) # 5, 4, 3, 2, 1
# Generator-based (simpler)
def chunked(iterable, size):
"""Yield successive chunks of a given size."""
chunk = []
for item in iterable:
chunk.append(item)
if len(chunk) == size:
yield chunk
chunk = []
if chunk:
yield chunk
data = list(range(10))
for batch in chunked(data, 3):
print(batch) # [0,1,2], [3,4,5], [6,7,8], [9]Use Cases
- Batch processing
- Lazy data loading
- Custom sequences
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
Protocol Classes for Structural Typing
Define interfaces with Protocol for duck-typing that works with static type checkers.
Best for: dependency injection
#python#protocol
pythonintermediate
Protocol
Advanced Python pattern: protocol
Best for: advanced programming
#python#advanced
javaintermediate
Custom Iterator and Iterable
Implement custom iterators and iterables for specialized data traversal and lazy sequence generation.
Best for: Lazy sequence generation for large datasets
#java#iterator
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation