Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python __enter__ and Context Managers

Learn how Python's __enter__ method works in context managers: the with-block protocol, implementation patterns, exception handling, and common pitfalls.

~4 min readPython
#context manager#__enter__#__exit__#with statement
Illustration of a Python context manager with enter and exit signs representing the __enter__ and __exit__ methods.

Python's __enter__ method is the hook that runs when a with block starts. It is part of the context manager protocol and is paired with __exit__, which runs after the block finishes. Understanding these two methods is essential for writing resource-safe code.

What __enter__ and __exit__ Actually Do

A context manager is an object that defines __enter__ and __exit__ methods. When you write with obj as x:, Python calls obj.__enter__() before the block runs and obj.__exit__(exc_type, exc_val, exc_tb) after the block finishes, even if an exception is raised. The __enter__ method can return any value, which becomes the target of the as clause. The __exit__ method is responsible for cleanup, such as closing a file or releasing a lock.

Because exceptions can interrupt code at any point, manually pairing setup and teardown logic is error-prone. The context manager protocol centralizes cleanup so you can rely on the with statement to call __exit__ automatically.

A Minimal Context Manager Implementation

Here is a minimal class-based context manager that manages a simple resource:

python
class ManagedResource: def __enter__(self): print("Acquiring resource") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Releasing resource") return False

Using it:

python
with ManagedResource() as res: print("Inside block")

When the with statement executes, __enter__ prints "Acquiring resource" and returns self. The as res binds that return value. After the block, __exit__ runs, prints "Releasing resource", and returns False to indicate that any exception should propagate normally.

The return False is important. If an exception occurred inside the block, Python passes it to __exit__; returning False lets the exception continue propagating. Returning True suppresses the exception, which is rarely what you want unless you handle it explicitly.

How the Return Value Flows

The value returned by __enter__ is not automatically the same object as the context manager. You can return anything. For example, a context manager might open a file and return the file handle:

python
class FileOpener: def __init__(self, path): self.path = path def __enter__(self): self.file = open(self.path) return self.file def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() return False

Here with FileOpener("data.txt") as f: binds f to the opened file object, not to the FileOpener instance. This is a common pattern for wrappers that need to expose a different resource.

When you implement __enter__, decide what the caller actually needs inside the block. If they need methods from the context manager itself, return self. If they need a separate resource, return that resource.

Handling Exceptions in __exit__

The __exit__ method receives three arguments: the exception type, the exception value, and the traceback object. If no exception occurs, all three are None. You can use this information to perform conditional cleanup or to suppress an exception by returning True.

For example, consider a context manager that ignores a specific exception:

python
class IgnoreValueError: def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is ValueError: print("Ignoring ValueError") return True return False

When you use with IgnoreValueError():, a ValueError raised inside the block is suppressed, and execution continues after the with block. Any other exception propagates normally.

Suppressing exceptions is a powerful tool, but it should be used sparingly. It can hide real bugs if you are not careful about which exceptions you catch.

Common Mistakes and How to Avoid Them

One frequent mistake is putting initialization logic in __enter__ that should be in __init__. The __init__ method creates the object, while __enter__ runs each time the object is used in a with statement. If the same object is used in multiple with blocks, __enter__ runs repeatedly. Keep one-time setup in __init__ and per-entry setup in __enter__.

Another mistake is forgetting to return a value from __enter__. If you do not include a return statement, Python implicitly returns None. Then with obj as x: binds x to None, which often leads to confusing AttributeError later. Always explicitly return something, even if it is self.

A third issue is not handling the return value of __exit__. Returning True from __exit__ suppresses an exception that is currently propagating. Unless that is deliberate, make sure your __exit__ returns False.

Performance and Resource Management Considerations

The real benefit of context managers is correctness: the with statement guarantees that __exit__ runs even if an exception occurs, which is exactly what you need for releasing locks or closing files. If you are entering and exiting many context managers in a hot loop, profile before optimizing; in most code the protocol overhead is not the bottleneck.

Resource management is where context managers shine: acquisition and release logic live in one place, reducing duplication and making code easier to audit. For example, a database connection context manager can ensure that connections are returned to a pool even when a query fails.

When to Use a Class-Based Context Manager vs contextlib

For simple cases, the contextlib.contextmanager decorator is often more readable. You write a generator function with a yield in the middle:

python
from contextlib import contextmanager @contextmanager def managed_resource(): print("Acquiring") try: yield "resource" finally: print("Releasing")

This is a more concise way to get the same cleanup guarantee. The value passed to yield becomes what as binds, so with managed_resource() as resource: gives you resource equal to the string "resource" inside the block.

A class-based context manager gives you more control when you need to store state on the instance, add helper methods, or expose the context manager object itself inside the block. With @contextmanager, calling the decorated function returns a wrapper object around the generator. The wrapper's __enter__ advances the generator and returns the value passed to yield, so the as target does not receive the wrapper object. In a class, __enter__ can return self or any other object.

Choose @contextmanager for a one-off context manager where the yield value is enough. Choose a class when you need the context manager object to carry state, support inheritance, or expose methods outside the with block.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.