Skip to the workspace
Pebellslearn by building

Python syntax & reference

Find the form you need, compare how it behaves, and open the complete explanation when you need more depth.

Python 3.10+ syntax; individual entries identify newer features. Browser exercises use the configured Python runner.

1 matching syntax entry

Context managers and cleanup

Learn in depth →

A context manager defines entry and exit behavior around a with block.

with resource() as value: ...

Example

from contextlib import contextmanager
@contextmanager
def owned():
    print("enter")
    try:
        yield "resource"
    finally:
        print("exit")
with owned() as value:
    print(value)

Result

enter
resource
exit

Watch for: Exit logic must define what happens on failures. Returning True from __exit__ suppresses the exception.

Practise this topic →
Complete explanation index (91 lessons indexed)

Writing Your Own Context Manager

Technical sources and review date

Original Pebells examples. Reviewed 2026-10-28.

Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.