Python, from Zero, for AILesson 65 of 89

Module 7 · Objects, generators and the shape a larger program takes

Context managers: the cleanup that runs even when the block raises

In this lesson

  • 8 min read
  • 7 reading sections
  • Knowledge check
  • Lesson 6 of 10 in this chapter

This chapter’s goalRestructure a growing script into classes and dataclasses with a swappable provider behind one interface, implement the dunder methods that let your objects work with for, len, in and with, write a decorator that retries or caches, run a type checker and act on its output, make the project installable as a command with pyproject.toml, and profile it to say from measurement rather than guesswork where the time goes.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:40Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 9Free · no account needed
Lesson steps

The problem with solves

Python
f = open(path, "w")
for item in items:
    f.write(process(item) + "\n")
f.close()

If process raises on the fortieth item, f.close() never runs. What happens to the thirty-nine lines already written depends on buffering: Python collects writes in memory and sends them to disk when the buffer fills or the file is closed. A short run that never closes can leave you with an empty file and a log full of successes. The file is closed when the process exits, but if the interpreter is shutting down because of an unhandled exception, whether that flush happens is not something to rely on.

The fix you already know:

Python
with open(path, "w") as f:
    for item in items:
        f.write(process(item) + "\n")

with promises that the file’s cleanup runs whether the block finishes, raises, or is left by return or break. This lesson is about what that promise is made of and how to make it for your own resources.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Context managers: the cleanup that runs even when the block raises’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/context-managers (Accessed: 21 November 2026).