Writing a context manager
There are two ways to make your own.
A class with two methods. __enter__ runs at the start of the with
block, and its return value is what as gets. __exit__ runs at the end.
Its full signature is __exit__(self, exc_type, exc, tb), describing the
exception if one happened, or None three times if not. If __exit__
returns True, the exception is swallowed. Return None or False to let
it carry on.
A generator decorated with contextlib.contextmanager. Code before
yield is the enter step, and code after it is the exit step. Wrap the
yield in try/finally, or the exit code is skipped when the block
raises. Forgetting that finally is a classic bug.
The generator form is shorter. The class form is better when the object has other methods or state.
Run it, then remove the try and finally in tag and see whether </p>
still prints.