1.3.4 · HinglishPython Intermediate

Context managers — with statement, `__enter__` - `__exit__`

1,513 words7 min readRead in English

1.3.4 · Coding › Python Intermediate


WHAT is a context manager?

with open("data.txt") as f:   # f = open(...).__enter__()
    data = f.read()
# f.__exit__(...) runs here, closing the file — even if read() raised

HOW with actually works (derive it from scratch)

Yeh statement

with EXPR as VAR:
    BODY

bilkul equivalent hai is de-sugared form ke:

mgr      = EXPR
VAR      = mgr.__enter__()          # ← return value goes to `as VAR`
try:
    BODY
except BaseException:
    # __exit__ gets the live exception info
    if not mgr.__exit__(*sys.exc_info()):
        raise                       # re-raise unless __exit__ returned True
else:
    mgr.__exit__(None, None, None)  # no exception → all three args are None
Figure — Context managers — with statement, `__enter__`  -  `__exit__`

Building one from first principles


Common mistakes (Steel-manned)


Recall Feynman: explain to a 12-year-old

Socho jaise library se book borrow karna. Jab tum andar jaate ho (__enter__) toh book checkout karte ho. Jab bahar jaate ho (__exit__) toh wapas karna zaroor padega — chahe raaste mein gir bhi jao. with block ek librarian ki tarah hai jo darwaze par khada hai aur pakka karta hai ki tum book lekar kabhi bahar nahi jaoge. Tumhe yaad rakhne ki zaroorat nahi; rule khud kar deta hai.


Recall

What two dunder methods define a context manager?
__enter__ and __exit__
What is bound to the as variable in a with statement?
The return value of __enter__
What are the three arguments passed to __exit__?
exc_type, exc_value, traceback (None×3 if no exception)
What does __exit__ returning a truthy value do?
Suppresses (swallows) the exception that occurred in the block
Does __exit__ run when the with body raises an exception?
Yes — it always runs, like a finally block
In @contextmanager, what splits setup from cleanup?
A single yield; code before is __enter__, code after (in finally) is __exit__
Why put cleanup in a finally inside a @contextmanager?
So cleanup runs even if the with-block body raises an exception
What is with EXPR as VAR: de-sugared to?
mgr=EXPR; VAR=mgr.enter(); try BODY; exit runs in try/finally with exc info
contextlib helper that ignores given exception types?
contextlib.suppress(*exceptions)

Connections

  • Exception handling — try-except-finallywith try/finally ke upar sugar hai.
  • Decorators@contextmanager ek decorator hai jo generator ko manager mein convert karta hai.
  • Generators and yield@contextmanager ke peeche single-yield trick hai.
  • File I/O — canonical with open(...) use case.
  • Threading and lockswith lock: release guarantee karta hai.
  • Dunder methods__enter__/__exit__ protocol family ka hissa hain.

Concept Map

requires

implements

implements

return value bound to

performs

desugars into

always runs

performs

returns

True

False or None

common uses

with statement

Context manager object

__enter__ method

__exit__ method

as VAR binding

try / finally desugar

Setup phase

Guaranteed cleanup

__exit__ return value

Exception suppressed

Files, locks, timers, DB conns