2

Is there any way to format a with statement so that I can establish a variable number of contexts? Like, sometimes I want four with statements, but other times I might only want two. As it is, I'm faced with the prospect of calling dummy versions of all the objects I could be using but aren't, then nesting my code in sixteen with statements with the dummy objects filling with statements I'm not using. Since I'm using Python 2.6.6 and don't even have support for the compacted syntax.

As an aside, are with statements really the only way to get cleanup code that works? There's really no other way to get anything that resembles a destructor method but isn't a mistake to use like the standard __del__ method?

jsbueno
  • 99,910
  • 10
  • 151
  • 209
Strill
  • 228
  • 3
  • 10
  • As for other ways to get clean-up code, one can always use the "finally" clause of "try" statements in simpler cases. – jsbueno Sep 05 '12 at 04:04

1 Answers1

4

contextlib.nested was made for that.

Example from the documentation:

from contextlib import nested

with nested(*managers):
    do_something()
dav1d
  • 5,917
  • 1
  • 33
  • 52
  • also worth pointing out the `with A() as a, B() as b: suite` form – Claudiu Sep 04 '12 at 20:39
  • 1
    Yes, but that doesn't work with a variable number of contexts and also not with Python 2.6 – dav1d Sep 04 '12 at 20:40
  • The one true issue is that since with statements now accept themultiple form, `contextlib.nested` will be marked as deprecated as of Python 3.3 - even though it is the only possible (clean) way of doing what the O.P. is asking for. – jsbueno Sep 05 '12 at 04:02
  • The problem here is how to create the managers assuring that an exception thrown while creating the last one won't leave all the rest relying on their `__del__()` for cleanup. – Rafał Dowgird Sep 28 '12 at 14:48