[Python-Dev] Multiline with statement line continuation

Steven D'Aprano steve at pearwood.info
Wed Aug 13 19:32:26 CEST 2014


On Wed, Aug 13, 2014 at 08:08:51PM +0300, yoav glazner wrote:
[...]
> Just a thought, would it bit wierd that:
> with (a as b, c as d): "works"
> with (a, c): "boom"
> with(a as b, c): ?

If this proposal is accepted, there is no need for the "boom". The 
syntax should allow:

# Without parens, limited to a single line.
with a [as name], b [as name], c [as name], ...:
    block

# With parens, not limited to a single line.
with (a [as name],
      b [as name],
      c [as name],
      ...
      ):
    block

where the "as name" part is always optional. In both these cases, 
whether there are parens or not, it will be interpreted as a series of 
context managers and never as a single tuple.

Note two things:

(1) this means that even in the unlikely event that tuples become 
context managers in the future, you won't be able to use a tuple 
literal:

    with (1, 2, 3):  # won't work as expected

    t = (1, 2, 3)
    with t:  # will work as expected

But I cannot imagine any circumstances where tuples will become context 
managers.


(2) Also note that *this is already the case*, since tuples are made by 
the commas, not the parentheses. E.g. this succeeds:

# Not a tuple, actually two context managers.
with open("/tmp/foo"), open("/tmp/bar", "w"):
   pass




-- 
Steven


More information about the Python-Dev mailing list