$ cat example.py import contextlib @contextlib.contextmanager def f(): print("start f") yield print("end f") print("before") with f(): print("inside") print("after") $ python3 example.py before start f inside end f after