BeginnerCoder

Lesson 26 — Writing a context manager

The with protocol

A class with enter and exit becomes a context manager: with Ctx(): calls enter at the start of the block and exit at the end, guaranteeing cleanup even on errors.

Why it matters: files, locks and DB sessions rely on it.

Want it another way?
Task

Add __exit__ to Ctx so it prints "done" when the with block ends.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Python Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.