Skip to content
UPEEC

Context Managers

The with statement guarantees setup and cleanup (files, locks, connections), even when errors occur.

Easy
Comments 0
from contextlib import contextmanager

@contextmanager
def powered(device):
    device.on()
    try:
        yield device
    finally:
        device.off()

with powered(motor) as m:
    m.run(5)

Class-based managers implement __enter__ and __exit__.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.