Codzy

Context managers (with)

You already know with open(...). The with keyword uses a context manager: it sets something up at the start of the block and cleans up at the end, automatically, even if an error occurs.

To create one, write a class with __enter__ (called at the start) and __exit__ (called at the end). Simpler still: the @contextmanager decorator from the contextlib module, with a yield that separates the before and the after.

class Timer:
    def __enter__(self):
        print("Start")
        return self

    def __exit__(self, exc_type, exc, tb):
        print("End")

with Timer():
    print("Working...")

from contextlib import contextmanager

@contextmanager
def tag(name):
    print("<" + name + ">")
    yield
    print("</" + name + ">")

with tag("b"):
    print("bold text")

Start the lesson