Context Managers
LockedLesson 24 of 60 · Syntax · Challenging
Finish these first:File I/O →Iterators and Generators →Or pass the tests below to unlock it now.
The big idea
with guarantees setup/teardown. Implement enter/exit or use contextlib.contextmanager.
Think of it like this: Think of syntax and expressions like labeled measuring cups in a kitchen: each cup holds a specific kind of ingredient, and operators combine them into a new measurement.
Read the lesson
with guarantees setup/teardown. Implement __enter__/__exit__ or use contextlib.contextmanager.
from contextlib import contextmanager
@contextmanager
def tag(name):
print(f"<{name}>")
try: yield
finally: print(f"</{name}>")
Quick check
Before writing code: What should `(lambda: [ (lambda cm: cm.__enter__() or cm.__exit__(ValueError, ValueError('x'), None))(suppress_errors()) ][0])()` return when your implementation of Context Managers is working?
Your challenge
Write context manager suppress_errors() that swallows Exception inside the block.
More learning tools(compare languages, visual guide, related lessons)
Compare with another language
See how Python compares side-by-side with Java.
Visual walkthrough
A diagram, a step-by-step animation, and short captions for Context Managers.
Learn this first
- File I/ONot yet
- Iterators and GeneratorsNot yet
Opens up next
This is the last lesson in this branch.