1. Introduction
The 'with' statement provides a clean, reliable way to acquire and release resources, such as files, locks, or network connections. It is built on top of the context manager protocol, ensuring that cleanup code runs automatically even if an exception occurs inside the block.
Cricket analogy: Renting a stadium's floodlights for a night match guarantees they're switched off after the game ends, even if the match is abandoned due to rain — just as Python's 'with' statement guarantees cleanup even if an exception occurs.
Using 'with open(...) as f' is the idiomatic way to work with files in Python, because it guarantees the file is closed as soon as the block exits, regardless of how it exits.
Cricket analogy: Checking out a scorebook from the pavilion 'with' a signed borrowing slip guarantees it's returned to the shelf when you're done, whether you finish the innings notes or get called away — just like 'with open(...) as f' guarantees the file closes.
2. Syntax
# Basic file usage
with open('example.txt', 'r') as f:
data = f.read()
# f is automatically closed here
# Multiple context managers
with open('in.txt') as fin, open('out.txt', 'w') as fout:
fout.write(fin.read())
# Custom context manager class
class MyContext:
def __enter__(self):
# setup code, return value bound to 'as'
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# cleanup code, runs even if an exception occurred
return False # False re-raises any exception3. Explanation
When Python enters a 'with' block, it calls the object's __enter__() method, and the value it returns is bound to the variable after 'as'. When the block finishes, whether normally or due to an exception, Python always calls __exit__(), which is where cleanup (like closing a file) happens.
Cricket analogy: Entering the dressing room triggers a kit manager to hand you your gear bag (like __enter__ returning a value bound to 'as'), and leaving triggers them to collect and lock it away again (like __exit__), whether you had a good innings or got out for a duck.
This __enter__/__exit__ pair is called the context manager protocol. File objects implement it so that 'with open(...) as f' automatically calls f.close() when the block ends, removing the need to manually manage try/finally blocks.
Cricket analogy: The pavilion's check-in/check-out system for kit is a protocol every player follows automatically, so no one needs a manual 'remember to return the bat' reminder — just as file objects implement __enter__/__exit__ so 'with open()' auto-closes without a try/finally.
The context manager protocol (__enter__ and __exit__) is what powers the 'with' statement. If __exit__ returns a truthy value, any exception raised inside the block is suppressed; returning False (or None) lets the exception propagate normally.
4. Example
import tempfile, os
class Timer:
def __enter__(self):
print('Entering context')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('Exiting context')
return False
path = os.path.join(tempfile.gettempdir(), 'demo_with.txt')
with open(path, 'w') as f:
f.write('Managed automatically')
with Timer() as t:
print('Inside the with block')
with open(path, 'r') as f:
print(f.read())
os.remove(path)5. Output
Entering context
Inside the with block
Exiting context
Managed automatically6. Key Takeaways
- 'with' automatically manages setup and cleanup via the context manager protocol.
- __enter__() runs at the start of the block; its return value is bound by 'as'.
- __exit__() always runs at the end of the block, even if an exception was raised.
- 'with open(...) as f' guarantees the file is closed without an explicit close() call.
- Multiple context managers can be combined in a single 'with' statement separated by commas.
Practice what you learned
1. Which two special methods make an object usable with the 'with' statement?
2. What value does 'with open('f.txt') as f' bind to f?
3. When does __exit__() get called relative to exceptions raised in the 'with' block?
4. What is the main advantage of 'with open(...) as f' over manual open()/close()?
5. If __exit__() returns True, what happens to an exception raised inside the 'with' block?
Was this page helpful?
You May Also Like
File Handling in Python
Understand how to open, read, write, and close files in Python using the built-in open() function and file modes.
Reading and Writing Files in Python
Explore the different methods for reading and writing file content, including read(), readline(), readlines(), write(), and writelines().
Exceptions in Python
What exceptions are, how Python's built-in exception hierarchy is structured, and how errors propagate through a program.
Decorators in Python
Learn how Python decorators use the @syntax to wrap functions, adding behavior like logging or timing without changing the original function's code.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics