Using Python's WITH keyword conditionally

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

1with open("sea.json", "r") as infile:
2    do_stuff(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:

1from contextlib import nullcontext
2
3with (open("sea.json", "r") as infile) if needs_open else nullcontext():
4    do_stuff(infile)

Have feedback or questions? Feel free to email me.