Python Schoolby trefilov
Шаг 1 из 4+120 XP

Контекстные менеджеры

with-блоки и contextlib для управления ресурсами.

class-based

class Timer:
    def __enter__(self):
        import time
        self.t = time.perf_counter()
        return self
    def __exit__(self, exc_type, exc, tb):
        print(f"took {time.perf_counter() - self.t:.4f}s")

via @contextmanager

from contextlib import contextmanager

@contextmanager
def tag(name):
print(f"<{name}>")
yield
print(f"</{name}>")