GCGrowCarrer

Context Managers

Locked

Lesson 24 of 60 · Syntax · Challenging

Finish these first:File I/O →Iterators and Generators →Or pass the tests below to unlock it now.

1

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.
Key words (tap to learn):
2

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}>")
3

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?

4

Your challenge

2 sample tests, 1 hidden

Write context manager suppress_errors() that swallows Exception inside the block.

Stuck? Get a hint (free)
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.

Mastery0%

Learn this first

Opens up next

This is the last lesson in this branch.