contextlib.nested deprecated

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Fri Mar 23 10:56:35 CET 2012


Hi,

I understand why contextlib.nested is deprecated.

But if I write a program for an old python version w/o the multiple form 
of with, I have (nearly) no other choice.

In order to avoid the following construct to fail:

     with nested(open("f1"), open("f2")) as (f1, f2):

(f1 wouldn't be closed if opening f2 fails)

I could imagine writing a context manager which moves initialization 
into its __enter__:

     @contextmanager
     def late_init(f, *a, **k):
         r = f(*a, **k)
         with r as c: yield c

Am I right thinking that

     with nested(late_init(open, "f1"), late_init(open, "f2")) as (f1, f2):

will suffice here to make it "clean"?


TIA,

Thomas



More information about the Python-list mailing list