Category: python
What Is a Context Manager?
Published on 27 Oct 2026
Explanation
A context manager performs setup and cleanup around a block. with invokes exit behavior even when an exception occurs.
Code:
with open('example.txt', 'w', encoding='utf-8') as file:
file.write('Learning Python')
Explanation
Using with ensures a file is closed when the block exits, including when an exception occurs.
Code:
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(file.closed)
Explanation
Class-based context managers implement __enter__ and __exit__. Returning True from __exit__ suppresses an exception, so do this only intentionally.
Code:
class Demo:
def __enter__(self): print('Enter'); return self
def __exit__(self, exc_type, exc_value, traceback):
print('Exit')
return False
with Demo(): print('Inside')
Explanation
A single with statement can manage multiple resources; exit occurs in reverse order of entry.
Code:
with open('input.txt', encoding='utf-8') as source, open('output.txt', 'w', encoding='utf-8') as target:
target.write(source.read())
Explanation
contextlib provides tools for creating and composing context managers, including redirect_stdout for capturing print output.
Code:
from contextlib import redirect_stdout
from io import StringIO
buffer = StringIO()
with redirect_stdout(buffer): print('Captured')
print(buffer.getvalue())