Using Python's WITH keyword conditionally

Sometimes you need to use with based on some condition, for instance

with open("sea.json", "r") as infile:

opens a file, but what if that file is already open? You’d want something like a conditional with, which does not exist in the base language syntax. However, since Python 3.7 you can use nullcontext:

from contextlib import nullcontext

with (open("sea.json", "r") as infile) if needs_open else nullcontext():

Have a question⁉ Contact me.