import os
from contextlib import contextmanager
@contextmanager
def cwd(path: str):
"""Temporarily chdir into `path`, restoring on exit."""
original = os.getcwd()
try:
os.chdir(path)
yield path
finally:
os.chdir(original)
with cwd("/tmp"):
print(os.getcwd()) # /tmp
print(os.getcwd()) # back to wherever you were
@contextmanager
def stopwatch(label: str):
import time
start = time.perf_counter()
yield
print(f"{label}: {(time.perf_counter() - start) * 1000:.2f} ms")
with stopwatch("expensive op"):
sum(i * i for i in range(1_000_000))
Create a free account and build your private vault. Share publicly whenever you want.