Advanced Python
Context Managers
Complete lesson for Context Managers using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Context Managers
Section: Advanced Python. Guarantee setup and teardown with with — files, locks, connections, and custom __enter__ / __exit__ or contextlib.
Why with exists
- Resources (files, sockets, locks) must be released even when errors happen.
withruns setup, binds an optional name, runs the block, then always runs teardown.- Real life: entering a room (enter), working, then locking the door behind you (exit) whether the meeting succeeded or not.
from io import StringIO
buf = StringIO("alpha\nbeta\n")
with buf as f:
print(f.readline().strip())
print("closed", buf.closed) The context manager protocol
__enter__runs on entry; its return value is bound byas.__exit__(exc_type, exc, tb)runs on the way out — with exception info if the block failed, else threeNones.- If
__exit__returns a true value, the exception is suppressed; returning false/None re-raises.
class DemoCM:
def __enter__(self):
print("enter")
return "resource"
def __exit__(self, exc_type, exc, tb):
print("exit", exc_type)
return False
with DemoCM() as value:
print("inside", value) Files and with open
with open(path) as f:closes the file even if youreturnor raise inside the block.- Prefer
Path.open()frompathlibthe same way. - Avoid relying on the garbage collector to close files — especially on Windows.
from pathlib import Path
import tempfile, os
path = Path(tempfile.gettempdir()) / "lcg_cm_demo.txt"
path.write_text("line1\nline2\n", encoding="utf-8")
with path.open(encoding="utf-8") as f:
print(f.read().splitlines())
os.remove(path) Nested and multiple context managers
- You can nest
withblocks or writewith A() as a, B() as b:— exits run in reverse order. - Reverse-order teardown mirrors stack unwinding: last acquired, first released.
- If acquisition of
Bfails,Astill cleans up.
class Named:
def __init__(self, name):
self.name = name
def __enter__(self):
print("enter", self.name)
return self.name
def __exit__(self, *args):
print("exit", self.name)
with Named("A") as a, Named("B") as b:
print("body", a, b) Locks as context managers
threading.Locksupportswith lock:— acquires on entry, releases on exit.- This avoids forgetting
release()after an exception in the critical section. - Same pattern appears with
multiprocessinglocks and many DB transaction helpers.
import threading
lock = threading.Lock()
total = 0
def add(n):
global total
with lock:
total += n
add(5)
add(7)
print(total) contextlib.contextmanager
- Write a generator: code before
yieldis enter; code after is exit;yieldthe bound value. - Put teardown in
finallyso it runs on success and failure. - This is often clearer than a full class for small helpers.
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
try:
yield name
finally:
print(f"</{name}>")
with tag("section") as name:
print("body", name) Advanced — Context Managers
Exception suppression in __exit__
- Return
Truefrom__exit__to swallow the exception — use sparingly and document why. contextlib.suppress(ErrorType)is the standard library form for intentional ignores.- Never suppress broadly (
Exception) without logging — you will hide bugs.
from contextlib import suppress
with suppress(ZeroDivisionError):
print(1 / 0)
print("continued") ExitStack for dynamic resources
ExitStacklets you enter a variable number of context managers in a loop.stack.callback(fn)registers arbitrary cleanup;stack.pop_all()transfers responsibilities.- Ideal when the set of files/connections is only known at runtime.
from contextlib import ExitStack, contextmanager
@contextmanager
def mark(name):
print("open", name)
try:
yield name
finally:
print("close", name)
with ExitStack() as stack:
names = [stack.enter_context(mark(n)) for n in ("one", "two", "three")]
print("using", names) Re-entrant and reusable managers
- Some managers are re-entrant (
RLock,redirect_stdoutin limited ways); many are not — do not assume. - A context manager instance may be single-use; factories/
@contextmanagerfunctions create fresh state eachwith. - Document whether your CM is reusable after exit.
async with
- Async code uses
__aenter__/__aexit__andasync withfor non-blocking setup/teardown. - Libraries like
aiohttpandasyncio.TaskGroup(3.11+) rely on this protocol. - Do not call async managers from sync
with— use the matching syntax.
import asyncio
class AsyncCM:
async def __aenter__(self):
print("aenter")
return self
async def __aexit__(self, exc_type, exc, tb):
print("aexit")
return False
async def main():
async with AsyncCM():
print("async body")
asyncio.run(main()) Design tips for custom managers
| Goal | Technique |
|---|---|
| Tiny helper | @contextmanager generator |
| Rich state / methods | Class with __enter__/__exit__ |
| N resources at runtime | ExitStack |
| Ignore known errors | suppress |
| Temporary monkeypatch | unittest.mock.patch (is a CM) |
Tricky Interview Points
Q1) What is a context manager?
Answer An object that defines setup/teardown around a with block via __enter__/__exit__ (or the async variants), guaranteeing cleanup.
Q2) What does the with statement guarantee?
Answer That __exit__ runs when the block ends, whether by normal completion, return, or an exception — unless the process is killed hard.
Q3) What are the arguments to __exit__?
Answer exc_type, exc_value, traceback. All None if the body succeeded; otherwise they describe the exception in flight.
Q4) How do you suppress an exception in __exit__?
Answer Return a true value from __exit__. Prefer contextlib.suppress for clarity when ignoring specific errors.
Q5) What does contextlib.contextmanager do?
Answer It turns a generator function into a context manager: before yield is enter, after yield (usually in finally) is exit, yielded value is the as target.
Q6) Why prefer with open over open().read()?
Answer with closes the file promptly and on errors. Manual close is easy to skip on exceptions or early returns.
Q7) In what order do multiple context managers exit?
Answer Reverse of entry order — like a stack.
Q8) What is ExitStack?
Answer A context manager that dynamically enters other context managers and ensures all are exited correctly, useful when the count is not fixed.
Q9) Are locks context managers?
Answer Yes. threading.Lock and many similar primitives support with lock: to acquire/release safely.
Q10) What is async with?
Answer The asynchronous form using __aenter__ and __aexit__, for awaitable setup and teardown in coroutine code.
Q11) Can __enter__ return self?
Answer Yes, commonly. Return whatever object should be bound by as — self, a connection, a file handle, etc.
Q12) What happens if __enter__ raises?
Answer The with body does not run, and __exit__ is not called for that manager. Earlier managers in a multi-with still exit.
Simple Programs
Timer context manager
import time
from contextlib import contextmanager
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.6f}s")
with timer("sum"):
total = sum(range(100000))
print(total) Temporary chdir
import os
from contextlib import contextmanager
from pathlib import Path
import tempfile
@contextmanager
def pushd(path):
prev = Path.cwd()
os.chdir(path)
try:
yield Path.cwd()
finally:
os.chdir(prev)
with pushd(tempfile.gettempdir()) as here:
print(here.exists())
print(Path.cwd().exists()) Suppress and count errors
class CountErrors:
def __init__(self):
self.errors = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if exc_type is not None:
self.errors += 1
print("suppressed", exc_type.__name__)
return True
return False
with CountErrors() as cm:
print(1 / 0)
print("errors", cm.errors) ExitStack over several buffers
from contextlib import ExitStack
from io import StringIO
buffers = [StringIO("A"), StringIO("B"), StringIO("C")]
with ExitStack() as stack:
files = [stack.enter_context(b) for b in buffers]
print("".join(f.read() for f in files)) Transactional list edits
from contextlib import contextmanager
@contextmanager
def transaction(data):
backup = list(data)
try:
yield data
except Exception:
data[:] = backup
raise
nums = [1, 2, 3]
try:
with transaction(nums):
nums.append(4)
raise RuntimeError("boom")
except RuntimeError:
pass
print(nums)
with transaction(nums):
nums.append(9)
print(nums) Problem Solving Tricks
- Always close resources with
with, not only in happy-pathfinallyyou might forget to write. - Put cleanup in
finallyinside@contextmanagergenerators. - Return
Truefrom__exit__only when suppression is intentional and tested. with A(), B():exitsBthenA.- Use
ExitStackinstead of deep nesting when opening N files. suppress(FileNotFoundError)beats emptyexcept: passfor readability.- Locks +
withprevent the classic “exception skipped release” bug. contextlib.redirect_stdoutis great for testing print-heavy helpers.- Prefer factory functions (
open_db()) that return managers over long-lived global connections. - For async libraries, mirror the same design with
async with.
Practice Programs List
- Write a
TempFileclass CM that creates and deletes a file path. - Implement
@contextmanagerversion of the same TempFile behaviour. - Use
ExitStackto open all.txtfiles in a folder and concatenate contents. - Build a CM that temporarily sets an environment variable and restores it.
- Demonstrate exception suppression vs re-raise with two
__exit__variants. - Wrap
threading.Lockusage in a tiny bank-account transfer example. - Write an
async withCM that sleeps briefly on enter and exit usingasyncio. - Create a transactional dict CM that rolls back keys on failure.