"with" expression ["as" name] ":"
but the expression itself can start with a parenthesis, so if it saw a
parenthesis after the "with" it would be ambiguous
I have used 'with' for so long that I was under the impression that the as-target was just a name as in MRAB's simplified syntax above, so imagine my surprise when I tried putting parentheses around the target and didn't get a syntax error straight away. I of course had to explore a bit, and came up with this. The ugly formatting of the with is simply to show that the parens behave as expected.
class opener:
def __init__(self, *files):
self.files = [open(file) for file in files]
def __enter__(self):
return [file.__enter__() for file in self.files]
def __exit__(self, *exc_info):
for file in self.files:
file.__exit__(*exc_info)
return True
with opener(
'x', 'y', 'z'
) as (
f1, f2, f3
):
print(f1)
print(f1.closed)
print(f2)
print(f3)
print(f1.closed)