Skip to content
PythonAdvanced Python Building Blocksbeginner25 min read

Context Managers

Master the with statement, automatic resource cleanup, exception handling, and Python's context manager protocol.

In this lesson, you will learn

  • ✓Explain why context managers are useful for managing resources.
  • ✓Use the with statement to open files safely and understand when they are closed.
  • ✓Describe the roles of __enter__() and __exit__() in the context manager protocol.
  • ✓Explain how context managers behave when an exception occurs inside a with block.
  • ✓Use contextlib.closing() and contextlib.contextmanager to manage resources.
  • ✓Implement and test a simple custom context manager.
  • ✓Identify common context manager mistakes and choose appropriate cleanup strategies.

1. Why do context managers exist?

Imagine opening a file, reading its contents, and then closing it. A straightforward approach is to call open(), perform the operation, and call close(). However, if an exception occurs before close() is reached, the cleanup statement might never execute.

A context manager provides a defined entry and exit process. The with statement uses that process so cleanup can happen when execution leaves the block, including when an exception is raised inside it.

Context managers are useful for files, locks, temporary resources, database transactions, and other operations that need predictable setup and cleanup. They do not automatically make every operation safe, but they give resources a structured lifecycle.

Manual cleanup versus the with statement

Manual cleanup versus the with statement
python
file = open('sample.txt', 'w', encoding='utf-8')
try:
file.write('Hello, Python!')
finally:
file.close()
 
with open('sample.txt', 'r', encoding='utf-8') as file:
print(file.read())
Output
Hello, Python!

The first part uses try and finally to ensure close() is attempted even if writing raises an exception. The second part uses with to manage the file's lifetime. The file is closed when execution leaves the block. The file must be closed before its contents are read in this example. The first finally block completes before the second with statement starts. The output contains one line with Hello, Python! followed by a newline.

Note

The with statement is usually the clearest choice for resources that already support the context manager protocol. Manual try/finally remains useful when a resource does not provide a suitable context manager.

2. The basic with statement

The general syntax is with expression as target:, followed by an indented block. Python evaluates the expression, enters the context, executes the block, and exits the context when the block finishes.

In a file example, open() returns a file object that supports the context manager protocol. The name after as refers to the object provided by its __enter__() method.

The indented block is the region where the resource is intended to be used. Once execution leaves that block, the context manager performs its exit behavior.

Write and read a file

Write and read a file
python
from pathlib import Path
 
path = Path('sample.txt')
 
with path.open('w', encoding='utf-8') as file:
file.write('saved')
 
with path.open('r', encoding='utf-8') as file:
print(file.read())
Output
saved

Path('sample.txt') represents the path used for the file. The first with block opens the file in write mode and writes the text saved. Leaving the first block closes the file. The second with block opens the same file in read mode and reads its contents. print() displays saved followed by a newline.

Note

Use raw strings or pathlib.Path when dealing with paths that contain backslashes on Windows. Always specify an encoding for text files when you need predictable text decoding and encoding.

3. How the context manager protocol works

A context manager is an object that implements the context manager protocol. The two central methods are __enter__() and __exit__().

__enter__() runs when the with statement enters the context. Its return value becomes the value assigned to the name after as. It can return the context manager itself or a different object that should be used inside the block.

__exit__() runs when the with block exits. Python calls it whether the block finishes normally or an exception is raised inside it. Its arguments provide information about an exception, if one occurred.

For a normal exit, __exit__() receives None for the exception type, value, and traceback. For an exceptional exit, it receives information about the exception. Returning a truthy value from __exit__() tells Python to suppress that exception; returning a false value allows the exception to propagate.

Cleanup code should be placed in __exit__() when it must run regardless of whether the block succeeds or fails.

Trace __enter__() and __exit__()

Trace __enter__() and __exit__()
python
class DemoContext:
def __enter__(self):
print('Entering')
return 'ready'
 
def __exit__(self, exc_type, exc_value, traceback):
print('Exiting')
return False
 
with DemoContext() as status:
print(status)
Output
Entering ready Exiting

Python calls __enter__() first, so Entering is printed. __enter__() returns the string ready, which is assigned to status. The body prints ready. When the body finishes, Python calls __exit__(), which prints Exiting. False means that this context manager does not suppress exceptions. No exception occurs in this example.

Note

The three parameters of __exit__() are conventionally named exc_type, exc_value, and traceback. They are None when the block exits normally.

4. What happens when an exception occurs?

An exception can interrupt the normal flow of a with block. Python still calls the context manager's __exit__() method, giving it a chance to clean up.

If __exit__() returns a false value, the original exception continues propagating unless the context manager raises a different exception during cleanup. If __exit__() returns a truthy value, the exception raised inside the block is suppressed.

Suppression should be intentional. Silently hiding unexpected exceptions can make a program appear successful when it has actually failed. A context manager that suppresses exceptions should have a clear reason to do so.

Cleanup runs when an exception occurs

Cleanup runs when an exception occurs
python
class DemoContext:
def __enter__(self):
print('Start')
return self
 
def __exit__(self, exc_type, exc_value, traceback):
print('Cleanup')
print(exc_type.__name__ if exc_type else 'No exception')
return False
 
try:
with DemoContext():
print('Inside')
raise ValueError('Something went wrong')
except ValueError:
print('Caught outside')
Output
Start Inside Cleanup ValueError Caught outside

The context is entered, so Start is printed. The block prints Inside and then raises ValueError. Python calls __exit__() with ValueError information before the exception leaves the with statement. Cleanup is printed, followed by ValueError, the exception type's name. Because __exit__() returns False, the exception propagates to the surrounding try statement. The except block catches it and prints Caught outside.

Caution

A return statement or an exception inside the block still triggers context exit. However, if __enter__() itself fails before completing, __exit__() for that same context manager is not called. If several context managers are used in one with statement, already-entered managers are exited if entering a later manager fails.

5. Built-in and standard-library context managers

File objects are common context managers, but Python's standard library provides others. For example, contextlib.closing() can manage an object that has a close() method but does not implement the context manager protocol.

closing() calls the object's close() method when the block exits. It does not provide file-specific behavior; it simply gives the object a context-managed cleanup lifecycle.

Some standard-library context managers temporarily change state, acquire and release locks, or help manage transactions. The correct context manager depends on the resource and the library being used.

Use contextlib.closing()

Use contextlib.closing()
python
from contextlib import closing
from io import StringIO
 
stream = StringIO('abc')
with closing(stream) as file_like:
print(file_like.read())
 
print(stream.closed)
Output
abc True

StringIO creates an in-memory text stream containing abc. closing(stream) ensures stream.close() is called when the with block exits. The first print displays abc. After the block, stream.closed is True, so the second print displays True.

Note

If an object already implements __enter__() and __exit__(), use its own context manager directly. Do not wrap it in closing() unnecessarily.

6. Create a context manager with contextlib.contextmanager

You do not always need to write a class with __enter__() and __exit__(). The contextlib module provides a contextmanager decorator that lets you create a context manager using a generator function.

In a generator-based context manager, code before yield performs setup, the value yielded is supplied to the as target, and code after yield performs cleanup.

The cleanup portion should usually use try/finally. That way, cleanup executes when the block finishes normally or when an exception is thrown into the generator at the yield point.

A generator decorated with contextmanager must yield exactly once for a successful context. A function that yields zero times or more than once does not implement the intended single-block lifecycle correctly.

A timer-like resource context

A timer-like resource context
python
from contextlib import contextmanager
 
@contextmanager
def managed_message():
print('Setup')
try:
yield 'resource ready'
finally:
print('Cleanup')
 
with managed_message() as message:
print(message)
Output
Setup resource ready Cleanup

Calling managed_message() creates the generator-based context manager. Entering the with block runs the generator until yield, so Setup is printed. The yielded string is assigned to message and printed by the body. When the block exits, execution resumes after yield and enters the finally cleanup path. Cleanup is printed before the with statement finishes.

Note

Use contextlib.contextmanager for small, focused setup/cleanup logic. Prefer a class when the context manager needs substantial state, several methods, or a more explicit object-oriented interface.

7. Common mistakes and best practices

A context manager only guarantees the behavior its implementation provides. It cannot guarantee that a network request succeeds, that a write reaches permanent storage, or that every external operation is reversible.

Do not assume a variable created with as must be the context manager itself. It is the value returned by __enter__(), which may be a separate resource object.

Do not use a return value from __exit__() as a general success indicator. Its truthiness controls whether an exception raised inside the block is suppressed.

Avoid broad exception suppression unless the application has a deliberate recovery strategy. Catch or suppress only errors that the program can handle correctly.

When writing a generator-based context manager, put cleanup in finally. Code after yield without finally may not run if an exception interrupts the generator.

Use descriptive names, narrow resource lifetimes, and tests that check both successful execution and failure paths.

A context manager should not accidentally hide errors

A context manager should not accidentally hide errors
python
class SafeContext:
def __enter__(self):
return self
 
def __exit__(self, exc_type, exc_value, traceback):
print('Cleanup complete')
return False
 
try:
with SafeContext():
raise ValueError('bad input')
except ValueError as error:
print(type(error).__name__)
Output
Cleanup complete ValueError

The cleanup message is printed when the block exits. Returning False means the context manager does not suppress ValueError. The surrounding except clause receives the exception and prints ValueError.

8. Summary

The with statement enters a context manager, executes a block, and exits the context when the block ends. This provides a reliable place for resource cleanup.

The context manager protocol uses __enter__() for entry and __exit__() for exit. The value returned by __enter__() is assigned to the as target. The return value of __exit__() determines whether an exception from the block is suppressed.

For a small custom context manager, implement a class with __enter__() and __exit__(), or use contextlib.contextmanager with setup before yield and cleanup in finally.

The main skill is not memorizing syntax. It is knowing when a resource needs cleanup, what happens on both normal and exceptional exits, and how to verify those behaviors.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Assuming with only closes files and has no other uses.

Why it happens: The with statement manages many resources beyond files, including locks, temporary resources, and transactions, by defining setup and cleanup behavior.

Incorrect Approach
script.py
python
Assuming with only closes files and has no other uses.
Correct Solution
script.py
python
Recognize that any object implementing the context manager protocol can define setup and cleanup behavior.

Key takeaway: Recognize that any object implementing the context manager protocol can define setup and cleanup behavior.

#2 Assuming the value after as is always the context manager object itself.

Why it happens: The object bound by as is whatever __enter__ returns; it can differ from the context manager object itself.

Incorrect Approach
script.py
python
Assuming the value after as is always the context manager object itself.
Correct Solution
script.py
python
Remember that the value assigned to the target is the return value of __enter__().

Key takeaway: Remember that the value assigned to the target is the return value of __enter__().

#3 Believing __exit__() runs only when the block succeeds.

Why it happens: __exit__ is invoked after the with block whether it completes normally or raises an exception, enabling cleanup in both cases.

Incorrect Approach
script.py
python
Believing __exit__() runs only when the block succeeds.
Correct Solution
script.py
python
It also runs when the block raises an exception, provided entry completed successfully.

Key takeaway: It also runs when the block raises an exception, provided entry completed successfully.

#4 Returning True from __exit__() without considering the exception.

Why it happens: Returning True from __exit__ suppresses the active exception, so only do this when intentionally handling that exception.

Incorrect Approach
script.py
python
Returning True from __exit__() without considering the exception.
Correct Solution
script.py
python
Return a truthy value only when suppressing the exception is an intentional and documented part of the design.

Key takeaway: Return a truthy value only when suppressing the exception is an intentional and documented part of the design.

#5 Writing cleanup after yield without a finally block.

Why it happens: If cleanup must run when a generator-based context manager exits through an exception, place cleanup in a finally block around the yield.

Incorrect Approach
script.py
python
Writing cleanup after yield without a finally block.
Correct Solution
script.py
python
Put required cleanup in try/finally so exceptions from the with-block do not skip it.

Key takeaway: Put required cleanup in try/finally so exceptions from the with-block do not skip it.

#6 Assuming __exit__() is called when __enter__() fails.

Why it happens: If __enter__ fails before returning successfully, __exit__ is not called for that context manager; setup code must handle partial initialization.

Incorrect Approach
script.py
python
Assuming __exit__() is called when __enter__() fails.
Correct Solution
script.py
python
If entry fails before it completes, that context manager's __exit__() is not called. Design acquisition logic accordingly.

Key takeaway: If entry fails before it completes, that context manager's __exit__() is not called. Design acquisition logic accordingly.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a context manager in Python?
Answer:
A context manager defines behavior for entering and exiting a block of code. It is commonly used to manage resources such as files and locks, ensuring that required cleanup happens when the block exits. The with statement is the usual way to use a context manager.
Q2:How does the with statement work internally?
Answer:
For a class-based context manager, Python evaluates the context expression, calls __enter__(), assigns its return value to the optional as target, executes the block, and calls __exit__() as the block exits. The exit method receives exception information if an exception was raised in the block.
Q3:What is the purpose of __enter__()?
Answer:
__enter__() performs context-entry setup and returns the object or value that should be assigned to the as target. For example, a file context manager returns a file object that can be used inside the block.
Q4:What are the parameters of __exit__()?
Answer:
__exit__(self, exc_type, exc_value, traceback) receives the exception type, exception instance, and traceback when an exception is active. These values are None when the block exits normally. The method is responsible for exit behavior and cleanup.
Q5:Can a context manager suppress an exception?
Answer:
Yes. If __exit__() returns a truthy value, Python suppresses the exception raised inside the with block. A false value allows it to propagate. Suppression should be intentional so unexpected failures are not hidden.
Q6:What is the difference between a class-based context manager and contextlib.contextmanager?
Answer:
A class-based context manager explicitly implements __enter__() and __exit__(). With contextlib.contextmanager, a generator function uses setup code before yield and cleanup code after yield, usually inside try/finally. The generator approach is often concise for simple resource lifecycles.
Q7:Why is finally important in a context manager?
Answer:
Cleanup often must happen whether the body succeeds, raises an exception, or exits early. A finally block is designed to run during normal or exceptional unwinding, making it suitable for releasing resources.
Q8:Does Python call __exit__() if __enter__() fails?
Answer:
No, not for that same context manager when its __enter__() fails before completing. Any resource acquired before the failure must be cleaned up by the entry logic itself. In a multi-manager with statement, managers that already entered are exited if a later entry fails.
Q9:When would you use contextlib.closing()?
Answer:
Use closing(obj) when an object has a close() method but does not provide its own context manager protocol. It ensures close() is called when the with block exits. Do not wrap objects unnecessarily when they already have suitable context management.
Q10:Can context managers be used for more than file handling?
Answer:
Yes. They can manage locks, temporary state, database transactions, network resources, and other operations that need setup and cleanup. The exact guarantees depend on the context manager's implementation and the resource it manages.

Key takeaways

  • The with statement gives resources a clear entry and exit lifecycle.
  • __enter__() performs setup and supplies the value assigned to the as target.
  • __exit__() runs when the block exits after successful entry, including exceptional exits.
  • A truthy return value from __exit__() suppresses an exception; a false value allows it to propagate.
  • Use try/finally for cleanup that must happen even when an exception interrupts execution.
  • contextlib.contextmanager creates generator-based context managers using setup, yield, and cleanup.
  • Context managers organize cleanup but do not guarantee every operation succeeds.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: