Unit 6 of 9 · about 4 hours · implement

Context managers, exceptions and deterministic cleanup

Deterministic cleanup separates scripts from services. Tracebacks are the primary diagnostic; the hierarchy decides their quality.

You'll be able to

  • Implement a resource-owning context manager in class and @contextmanager forms, with cleanup proven on success and exception paths.
  • Derive the cleanup sequence for nested managers with failing handlers.
  • Design a small exception hierarchy that preserves cause and maps to actionable command-line errors.

Covers

Context managers, ownership and deterministic cleanupException hierarchies, chaining, cleanup and actionable messages
1

Read

In this order, only the parts listed

0 of 6 done

  1. Context managersStas' Python Cookbook - selected path

    Classes and Objects: Context managers (the @contextmanager opened() pattern with try/finally); nullcontext for conditional with blocks

  2. Exceptions and error handlingStas' Python Cookbook - selected path

    Raising and catching (try/except/else/finally); Re-raising and chaining (raise from, from None); Custom exceptions; Good habits

  3. The try statementPython language reference

    Section 8.4 with 8.4.2 except*: groups split across clauses; else runs only without exceptions; finally always runs

  4. The with statementPython language reference

    Section 8.5: __enter__ and __exit__ protocol; a true __exit__ return suppresses the exception

  5. Exception ChainingAlgoMaster Python - structured revision

    The Exception Chaining lesson and its exercise; trace __cause__ versus __context__

  6. Context ManagersAlgoMaster Python - structured revision

    The Context Managers lesson and Exercise: Context Managers; then the with Statement lesson

2

Focus on

  • Exceptions in the with body are thrown into the @contextmanager generator at the yield point; the finally clause still runs before propagation.
  • __exit__ returning true suppresses; anything falsy re-raises. Swallowing by accident hides the failure the caller must see.
  • raise New from e keeps the cause; from None hides context deliberately. A bare raise re-raises the same exception with its traceback.
  • ExceptionGroup splits across except* clauses since Python 3.11: handled members are removed and the rest keeps propagating.
Common mistakes · 3
  • A bare except: swallows KeyboardInterrupt and SystemExit. Catch Exception at broadest, and re-raise what you do not handle.
  • An exception raised in finally or in __exit__ replaces the in-flight one. Keep cleanup paths total and narrow.
  • Catching an ExceptionGroup with except instead of except*. Plain except matches the whole group object and never the members.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write a @contextmanager owning a temp file plus a two-level ConfigError hierarchy with a CLI exit-code map. Prove the file closes on an inner ValueError and that the mapped error keeps its __cause__.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Where does an exception raised in a with body surface inside a @contextmanager generator?Answer

    At the yield point, as if the yield raised it. try/finally around the yield runs cleanup, then the exception propagates unless caught.

  2. 2.What is the difference between raise E from e, raise E from None and bare raise?Answer

    from e sets __cause__ and shows both tracebacks; from None suppresses the context; bare raise re-raises the active exception unchanged.

  3. 3.except* ValueError handles half an ExceptionGroup. What happens to the rest?Answer

    The remaining members propagate as a group. except* subtracts matches; unmatched members keep traveling.

  4. 4.When does the else clause of try run, and what is it for?Answer

    Only when no exception occurred. It separates code that must not be protected from the risky block, so its own failures stay distinct.

5

Practice

You're done when

Your manager closes the resource on success, exception and inner-raise paths, and your hierarchy maps each failure to one actionable message with its cause intact.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 5 more in the section
  • Stas' Python Cookbook - selected pathStas Bekman · primary

    Run Part I on dictionaries, iteration, functions, closures, decorators, classes and context managers; Part II on modules, files, paths, environment and arguments; and Part IV on versions, dependencies, packaging and code quality. Finish by building one src-layout package from a blank directory.

  • Python language referencePython Software Foundation · required

    Check Data model, Execution model, Import system and Exceptions whenever a claim depends on Python semantics. These pages are the authority when the course and a runtime observation disagree.

  • AlgoMaster Python - structured revisionAlgoMaster · support

    Use Functions, Modules and Packages, OOP, Advanced OOP, Exception Handling, Iterators and Generators, Type Hints and Annotations only after the cookbook pass. Open it for recall practice or a diagnosed weak mechanism, not as a second complete course.

Also in this section

  • Packaging Python ProjectsPython Packaging Authority · required

    Follow the packaging tutorial once from a blank directory, using a src layout, pyproject.toml, an isolated build and a clean-environment installation test.

  • dataclasses - data classesPython Software Foundation · reference

    Read the @dataclass parameters (eq, order, frozen, slots), field() with default_factory, frozen instances, post-init processing, replace, asdict and astuple. Use for the validated frozen dataclass in attributes-protocols-dataclasses.

  • typing - type hints and protocolsPython Software Foundation · reference

    Read Protocols for structural typing and runtime_checkable limits, Generics for TypeVar generics, and assert_type for narrowing checks. Use for the Protocol and narrowing parts of type-hints-protocols; PEP 695 syntax itself is in the language reference.

  • gc - cycle garbage collectorPython Software Foundation · reference

    Read the cycle collector interface: collect, get_count, garbage and disable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs.

  • weakref - weak referencesPython Software Foundation · reference

    Read weak-reference objects (ref callbacks, proxy objects) and the WeakValueDictionary example. Use for the weak-reference part of refcounting-gc-weakrefs.