Python __enter__ Method
Last modified November 17, 2026 Python 3.15
The with statement calls __enter__ when a context
is opened, and its return value is bound to the as target. The
method is the setup half of the context manager protocol; __exit__
handles the teardown. This article shows the dispatch, the return value,
resource setup, failure during setup, and the contextlib shortcut.
How the with statement calls __enter__
with obj as value is evaluated as
value = type(obj).__enter__(obj). The lookup happens on the type, so
an __enter__ attribute stored on the instance is ignored. When the
block ends, Python calls type(obj).__exit__(obj, ...). The example
records the order of the two calls and also invokes the hook directly to show
the dispatch.
class Context:
def __init__(self):
self.events = []
def __enter__(self):
self.events.append("enter")
return "resource"
def __exit__(self, exc_type, exc_val, exc_tb):
self.events.append("exit")
ctx = Context()
with ctx as value:
print("body:", value)
ctx.events.append("body")
print("events:", ctx.events)
print("direct:", Context.__enter__(Context()))
class Shadowed(Context):
def __init__(self):
super().__init__()
self.__enter__ = lambda: "instance"
with Shadowed() as value:
print("shadowed:", value)
The events list shows enter, then the body, then
exit. The as target receives the string returned by
__enter__, not the context manager object. Calling
Context.__enter__(Context()) directly gives the same return value,
confirming that the method lives on the class. The subclass stores an
__enter__ on the instance, yet with still calls the
class method and binds resource.
$ python basic_enter.py body: resource events: ['enter', 'body', 'exit'] direct: resource shadowed: resource
The return value becomes the as target
__enter__ may return self, a wrapped
resource, or any other object. The caller receives exactly that object; there
is no implicit conversion.
class Wrapper:
def __init__(self, data):
self.data = data
def describe(self):
return f"wrapped {self.data}"
class Manager:
def __enter__(self):
return Wrapper("payload")
def __exit__(self, exc_type, exc_val, exc_tb):
pass
with Manager() as value:
print(type(value).__name__, value.describe())
Here the manager returns a Wrapper rather than itself,
so value is a Wrapper and offers its own
describe() method. Returning self is convenient when
the manager is also the object used inside the block; returning a separate
resource is the usual choice for files and connections.
$ python return_value.py Wrapper wrapped payload
Setting up a resource
Setup belongs in __enter__, so the resource is ready
before the body runs. The matching __exit__ releases it on the way
out. A flag makes the lifetime visible in the output.
class Resource:
def __init__(self, name):
self.name = name
self.open = False
def __enter__(self):
print(f"open {self.name}")
self.open = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"close {self.name}")
self.open = False
def read(self):
return f"data from {self.name}"
with Resource("db") as res:
print(res.read(), res.open)
print("after:", res.open)
The resource is open inside the with block and closed
afterwards. Because __exit__ is called even when the body raises an
exception, cleanup in that method is reliable; that behaviour is covered in the
__exit__ article.
$ python resource_setup.py open db data from db True close db after: False
When setup fails
If __enter__ raises, the exception propagates
immediately. The body is not executed, the as target is never
bound, and __exit__ is not called. Any resource acquired before the
failure must be released inside __enter__ itself.
class FailingManager:
def __enter__(self):
print("enter started")
raise RuntimeError("setup failed")
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit called")
try:
with FailingManager() as value:
print("body")
except RuntimeError as e:
print(type(e).__name__, e)
Only enter started and the exception are printed; the
exit message never appears. A robust hook wraps partial setup in
try/except and cleans up before re-raising.
$ python enter_error.py enter started RuntimeError setup failed
The contextlib shortcut
The contextlib.contextmanager decorator builds a context
manager from a generator. The code before yield runs in
__enter__, the yielded value becomes the as target,
and the code after yield runs in __exit__.
from contextlib import contextmanager
@contextmanager
def resource(name):
print(f"open {name}")
try:
yield name.upper()
finally:
print(f"close {name}")
with resource("db") as value:
print("body:", value)
The output matches a hand-written pair of methods. The
try/finally guarantees that the closing message is printed even if
the body fails. Use this decorator when setup and teardown fit in one function;
write the two methods explicitly when state must be shared across calls.
$ python contextlib_alt.py open db body: DB close db
Best practices
A context manager is easiest to reason about when its two halves are balanced:
- Keep
__enter__focused on setup and return the object the caller will use. - Remember that the lookup is on the type; an instance attribute named
__enter__has no effect. - Release any partially acquired resource inside
__enter__if setup can fail. - Make
__exit__safe to call even when setup only partly succeeded. - Consider
@contextmanagerfor simple setup/teardown pairs.
Source
object.__enter__ - Python documentation
contextlib - Python documentation
The with statement - Python documentation
In this article we have implemented the __enter__
method. We have covered the with dispatch, the as
return value, resource setup, setup failures, and the
contextlib alternative. For related topics, see
Python __exit__ method,
Python context managers, and
Python with keyword.
Author
List all Python tutorials.