5. Use nullcontext for optional context managers

Use nullcontext() when a value is sometimes managed by a context manager and sometimes already available.

This keeps the control flow uniform: the code can always use with even when one branch does not need resource management. That usually reads better than splitting the main logic across two branches just to handle setup differently.

Note

Python 3.7+

5.1. Don’t do this

1if filename is None:
2    data = stream.read()
3else:
4    with open(filename) as stream:
5        data = stream.read()

5.2. Do this

1from contextlib import nullcontext
2
3cm = open(filename) if filename is not None else nullcontext(stream)
4with cm as fh:
5    data = fh.read()