Iterators and Context Managers
Iterators
An iterator is an object that implements the __iter__()
and __next__()
methods, allowing traversal through elements one at a time.
Example of an Iterator
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
value = self.current
self.current += 1
return value
# Using the iterator
counter = Counter(1, 5)
for num in counter:
print(num)
Output:
1
2
3
4
5
Context Managers
A context manager is an object that properly manages resources using the with
statement. It ensures resources (like files, network connections) are released properly after use.
Example of a Context Manager using with
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
# Using the context manager
with FileManager("example.txt", "w") as file:
file.write("Hello, world!")
# The file is automatically closed outside the `with` block.
Summary
- Iterators implement
__iter__()
and__next__()
. - Context Managers use
with
to manage resources efficiently (with open("file.txt", "r") as f:
).