
On Fri, Nov 15, 2019 at 9:41 PM Jonathan Fine jfine2358@gmail.com wrote:
Hi All
The original poster wanted, inside 'with' context management, to open several files. Context management is, roughly speaking, deferred execution wrapped in a try ... except .... statement.
The lambda construction also provides for deferred execution. Perhaps something like
with helper(lambda: open('a'), open('b'), open('c')) as a, b c: pass
would do what the original poster wanted, for a suitable value of helper. It certainly gives the parentheses the OP wanted, without introducing new syntax.
However, map also provides for deferred execution. It returns an iterable (not a list).
x = map(open, ['a', 'b', 'c']) x
<map object at 0x7f8cb5653b70>
next(x)
FileNotFoundError: [Errno 2] No such file or directory: 'a'
So the OP could even write:
with helper(map(open, ['a', 'b', 'c'])) as a, b, c: pass
for a (different) suitable value of helper.
I hope this helps.
I don't understand your point about deferred execution here. But a vitally important part of multi-with semantics is that, if something goes wrong while opening "c", the files "b" and "a" need to be properly closed. Trying to write a helper() that is capable of doing this would be extremely difficult, possibly impossible (and would need to do its own mapping, otherwise it IS impossible).
ChrisA