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
@contextmanagerforms, 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
Read
In this order, only the parts listed
0 of 6 done
- Context managersStas' Python Cookbook - selected path
Classes and Objects: Context managers (the
@contextmanageropened()pattern withtry/finally);nullcontextfor conditionalwithblocks - Exceptions and error handlingStas' Python Cookbook - selected path
Raising and catching (
try/except/else/finally); Re-raising and chaining (raisefrom,from None); Custom exceptions; Good habits - The try statementPython language reference
Section 8.4 with 8.4.2
except*: groups split across clauses;elseruns only without exceptions;finallyalways runs - The with statementPython language reference
Section 8.5:
__enter__and__exit__protocol; a true__exit__return suppresses the exception - Exception ChainingAlgoMaster Python - structured revision
The Exception Chaining lesson and its exercise; trace
__cause__versus__context__ - Context ManagersAlgoMaster Python - structured revision
The Context Managers lesson and Exercise: Context Managers; then the
withStatement lesson
Focus on
- Exceptions in the
withbody are thrown into the@contextmanagergenerator at theyieldpoint; thefinallyclause 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 ekeeps the cause;from Nonehides context deliberately. A bareraisere-raises the same exception with its traceback.ExceptionGroupsplits acrossexcept*clauses since Python 3.11: handled members are removed and the rest keeps propagating.
Common mistakes · 3
- A bare
except: swallowsKeyboardInterruptandSystemExit. CatchExceptionat broadest, and re-raise what you do not handle. - An exception raised in
finallyor in__exit__replaces the in-flight one. Keep cleanup paths total and narrow. - Catching an
ExceptionGroupwithexceptinstead ofexcept*. Plainexceptmatches the whole group object and never the members.
Try it yourself
Closed-book, before checking anything
@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__.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Where does an exception raised in a
withbody surface inside a@contextmanagergenerator?AnswerAt the
yieldpoint, as if theyieldraised it.try/finallyaround theyieldruns cleanup, then the exception propagates unless caught.2.What is the difference between
raise E from e,raise E from Noneand bareraise?Answerfrom esets__cause__and shows both tracebacks;from Nonesuppresses the context; bareraisere-raises the active exception unchanged.3.
except* ValueErrorhandles half anExceptionGroup. What happens to the rest?AnswerThe remaining members propagate as a group.
except*subtracts matches; unmatched members keep traveling.4.When does the
elseclause oftryrun, and what is it for?AnswerOnly when no exception occurred. It separates code that must not be protected from the risky block, so its own failures stay distinct.
Practice
- AlgoMaster Python: Exercise: Context Managers
Exercises 1 to 5, especially Exercise 3: Close a File After an Exception and Exercise 5: Build a Generator Context Manager
Then prove cleanup on the exception path in your own file.
- AlgoMaster Python: Exercise: Exception Chaining
Exercises 1 to 5: implicit context,
raisefroma cause,from None, the two traceback bridge sentences, and a cause that differs from the contextDraw the
__cause__chain for each answer.
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
@dataclassparameters (eq,order,frozen,slots),field()withdefault_factory, frozen instances, post-init processing,replace,asdictandastuple. 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_checkablelimits, Generics forTypeVargenerics, andassert_typefor narrowing checks. Use for theProtocoland 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,garbageanddisable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs. - weakref - weak referencesPython Software Foundation · reference
Read weak-reference objects (
refcallbacks,proxyobjects) and theWeakValueDictionaryexample. Use for the weak-reference part of refcounting-gc-weakrefs.