Hacker News new | ask | show | jobs
by hchasestevens 2054 days ago
Do be aware that https://docs.python.org/3.9/library/contextlib.html#contextl... also exists as of 3.7 -- you can do

  ctx_mgr = foo() if bar else nullcontext()
  with ctx_mgr:
      ...
if you like.
1 comments

Or even, from Python 3.8:

    with (ctx_mgr := foo() if bar else nullcontext()):
        ...