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():

To contact me, send an email anytime or leave a comment below.