contextlib

say it: “KON-tekst-lib” /ˈkɑntɛkstˌlɪb/

A standard module for writing your own context managers easily.

What is contextlib?

contextlib is a standard module that makes writing your own context manager easy: a generator with one yield, marked @contextmanager.

from contextlib import contextmanager
import time

@contextmanager
def timer(label):
    start = time.time()
    yield
    print(f"{label} took {time.time() - start:.2f}s")

with timer("Report"):
    time.sleep(1)

Level: Freelancer · More Python terms at this level

Updated