01 / 21

Context Managers
The with Statement

Master Python's context managers to safely manage resources: files, connections, and locks: all with automatic cleanup guaranteed.

Python

What Is a Resource?

In programming, a resource is anything your program borrows from the operating system that must eventually be returned. If you forget to return it, bad things happen: memory leaks, locked files, or crashed databases.

Files
Opened for reading or writing: the OS limits how many can be open at once.
Connections
Database or network sockets: each one consumes memory and ports.
Locks
Thread locks for concurrency: forgetting to release causes deadlocks.

The Problem Without with

Without context managers, you must manually open and close every resource. If an error occurs between open and close, the resource leaks:

f = open('data.txt', 'r') content = f.read() # What if this line crashes? f.close() # This line NEVER runs!

The try/finally Fix

Python's try/finally block guarantees cleanup runs even if an exception occurs. But it's verbose and easy to get wrong:

f = open('data.txt', 'r') try: content = f.read() # process content... finally: f.close() # Always runs, even on error

The with Statement

A context manager is any object that defines how to set up and tear down a resource. The with statement is the syntax that activates it:

with open('data.txt', 'r') as f: content = f.read() # f is automatically closed when this block ends # Even if an exception occurs, f.close() is called!

How with Works Under the Hood

__enter__() Set up resource with body Your code runs OK Error __exit__() Clean up __enter__(self) Called when entering the with block. Returns the resource (bound to "as" var). __exit__(self, exc_type, exc_val, tb) Called when leaving the with block. Always runs: handles cleanup + exceptions. Context Manager Protocol Any object with __enter__ + __exit__ is a context manager

The Context Manager Protocol

To be a context manager, an object must implement two magic methods. This is Python's "contract" for resource management:

1
__enter__(self): Called at the start of the with block. Sets up the resource and returns the value bound to the as variable.
2
__exit__(self, exc_type, exc_val, traceback): Called when leaving the with block. Performs cleanup. Receives exception info (or None if no error).

with vs try/finally

✕ Without with
f = open('f.txt') try: data = f.read() finally: f.close()
vs
✓ With with
with open('f.txt') as f: data = f.read()

How to Apply Context Managers

1
Identify the resource: Is there something that needs opening AND closing? Files, connections, locks.
2
Use the with keyword: Write with resource_expression as variable: to enter the context.
3
Work inside the block: All resource operations go inside the indented body.
4
Trust the cleanup: When the block ends (normally or via exception), __exit__ runs automatically.

Example 1: Reading a File

# Read all lines from a file safely with open('students.txt', 'r') as f: for line in f: print(line.strip()) # Here, f is already closed print(f.closed) # True

Example 2: Writing to a File

names = ['Alice', 'Bob', 'Charlie'] with open('output.txt', 'w') as f: for name in names: f.write(name + '\n') # File is flushed and closed automatically # All data is safely written to disk

Example 3: Custom Context Manager

import time class Timer: def __enter__(self): self.start = time.time() return self def __exit__(self, exc_type, exc_val, tb): elapsed = time.time() - self.start print(f'Elapsed: {elapsed:.2f}s') return False with Timer() as t: # code to time goes here total = sum(range(1000000))

Multiple Context Managers

You can nest or combine context managers. Python lets you use multiple with targets in a single statement, separated by commas:

# Nested (works in all Python versions) with open('input.txt') as src: with open('output.txt', 'w') as dst: dst.write(src.read()) # Combined (Python 2.7 / 3.1+): cleaner with open('in.txt') as src, open('out.txt', 'w') as dst: dst.write(src.read())

The contextlib Shortcut

Writing a full class with __enter__ and __exit__ is verbose. Python's contextlib module provides a decorator that turns a generator function into a context manager:

from contextlib import contextmanager import time @contextmanager def timer(): start = time.time() yield # with body runs here elapsed = time.time() - start print(f'Elapsed: {elapsed:.2f}s') with timer(): total = sum(range(1000000))

Common Mistakes

✕ Using the variable outside
Accessing the resource after the with block exits. The file is closed, so reads/writes will raise a ValueError.
✕ Forgetting "as"
Writing with open('f.txt'): without as f means you have no variable to reference the file inside the block.
✕ Returning True in __exit__
Accidentally suppressing all exceptions by returning True in __exit__ hides bugs silently. Only do this intentionally.

Summary Comparison

Manual close try/finally with statement
Cleanup guaranteed? No Yes Yes
Lines of code 3+ 5+ 2
Error-prone? Very Somewhat No
Readable? OK Verbose Excellent
Customizable? No Yes Yes

Question 1 of 5

What two methods must an object implement to be a context manager?

Question 2 of 5

What happens to the file f if an exception is raised inside this with block?

with open('data.txt') as f: result = 1 / 0 # ZeroDivisionError!

Question 3 of 5

In a @contextmanager decorated generator, which keyword separates the setup code from the cleanup code?

Question 4 of 5

What is the output of this code?

with open('test.txt', 'w') as f: f.write('hello') print(f.closed)

Question 5 of 5

Which of the following is the primary advantage of using a with statement over a try/finally block?