Is there a way to begin a block of code with a with statement, but conditionally?
Something like:
if needs_with(): with get_stuff() as gs: # do
It was hard to find @farsil's nifty Python 3.3 one-liner, so here it is in its own answer:
with ExitStack() if not needs_with() else get_stuff() as gs: # do stuff
Note that ExitStack should come first, otherwise get_stuff() will be evaluated.
get_stuff()