1. Concept library
  2. Python Foundations
  3. Module 7: Files and exceptions

Concept

Context managers

The with statement guarantees that something is cleaned up, such as a file closed or a lock released, even if the block raises. Any object with __enter__ and __exit__ can be used this way.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what the with statement guarantees, even when the block raises
  2. Write code that opens a file with with and reads it safely
  3. Explain what __enter__ and __exit__ do and when each runs

In practice

A few lines that show Context managers doing its job.

Python
from contextlib import contextmanager
import time

@contextmanager
def timed(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        print(label, round(time.perf_counter() - start, 3), "s")

with timed("sum"):
    total = sum(range(1_000_000))

The common mistake

Watch for

Calling open() without with and relying on the file closing itself. On an exception, or in other Python implementations, the file can stay open and buffered writes may never land.

What to know first

Your roadmap puts these before Context managers, unless you already know them.

How it stays learned

Once a session shows you understand Context managers, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← try and except