Skip to main content

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.

L1

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.
  • with runs 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 by as.
  • __exit__(exc_type, exc, tb) runs on the way out — with exception info if the block failed, else three Nones.
  • 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 you return or raise inside the block.
  • Prefer Path.open() from pathlib the 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 with blocks or write with A() as a, B() as b: — exits run in reverse order.
  • Reverse-order teardown mirrors stack unwinding: last acquired, first released.
  • If acquisition of B fails, A still 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.Lock supports with lock: — acquires on entry, releases on exit.
  • This avoids forgetting release() after an exception in the critical section.
  • Same pattern appears with multiprocessing locks 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 yield is enter; code after is exit; yield the bound value.
  • Put teardown in finally so 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)
L2

Advanced — Context Managers

Exception suppression in __exit__

  • Return True from __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

  • ExitStack lets 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_stdout in limited ways); many are not — do not assume.
  • A context manager instance may be single-use; factories/@contextmanager functions create fresh state each with.
  • Document whether your CM is reusable after exit.

async with

  • Async code uses __aenter__ / __aexit__ and async with for non-blocking setup/teardown.
  • Libraries like aiohttp and asyncio.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

GoalTechnique
Tiny helper@contextmanager generator
Rich state / methodsClass with __enter__/__exit__
N resources at runtimeExitStack
Ignore known errorssuppress
Temporary monkeypatchunittest.mock.patch (is a CM)
L3

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.

L4

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)
L5

Problem Solving Tricks

  • Always close resources with with, not only in happy-path finally you might forget to write.
  • Put cleanup in finally inside @contextmanager generators.
  • Return True from __exit__ only when suppression is intentional and tested.
  • with A(), B(): exits B then A.
  • Use ExitStack instead of deep nesting when opening N files.
  • suppress(FileNotFoundError) beats empty except: pass for readability.
  • Locks + with prevent the classic “exception skipped release” bug.
  • contextlib.redirect_stdout is 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.
L6

Practice Programs List

  1. Write a TempFile class CM that creates and deletes a file path.
  2. Implement @contextmanager version of the same TempFile behaviour.
  3. Use ExitStack to open all .txt files in a folder and concatenate contents.
  4. Build a CM that temporarily sets an environment variable and restores it.
  5. Demonstrate exception suppression vs re-raise with two __exit__ variants.
  6. Wrap threading.Lock usage in a tiny bank-account transfer example.
  7. Write an async with CM that sleeps briefly on enter and exit using asyncio.
  8. Create a transactional dict CM that rolls back keys on failure.