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. e., < 2.7), 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, because the contextmanager is not entered)
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”?
The use case given is just an example. Imagine you have a list of files whose length is not prematurely known. Then neither the 2.7 composed with is usable nor the pre-2.7 nested way with several indented with statements.
I probably have to be more verbose about that.
The said worharound solves the prolem at first glance: calling the function is executed in a secure place so that failure can be detected and dealt with appropriately.
My question is: Does it cure the flaw, or do I get other problems?
I now saw that my solution (
late_init()) would probably cure the first quirk:But the second one:
(which is probably caused by the skipped
yield varsfromnested()) is not covered by that.So either
nested()should be avoided,nested()should be replaced with a better one or