Conditional with statement in Python
问题 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 nearly the same large block of stuff, # involving gs or not, depending on needs_with() To clarify, one scenario would have a block encased in the with statement, while another possibility would be the same block, but not encased (i.e., as if it wasn't indented) Initial experiments of course give indentation errors.. 回答1: If you want to avoid