[Python-ideas] with statement: multiple context manager

Guido van Rossum guido at python.org
Sun Mar 1 20:46:17 CET 2009

On Sun, Mar 1, 2009 at 5:49 AM, Christian Heimes <lists at cheimes.de> wrote:
> On a regularly basis I'm bothered and annoyed by the fact that the with
> statement takes only one context manager. Often I need to open two files
> to read from one and write to the other. I propose to modify the with
> statement to accept multiple context manangers.
> Example
> =======
> The nested block::
>  with lock:
>      with open(infile) as fin:
>          with open(outfile, 'w') as fout:
>              fout.write(fin.read())
> could be written as::
>  with lock, open(infile) as fin, open(outfile, 'w') as fout:
>      fout.write(fin.read())
> The context managers' __enter__() and __exit__() methods are called FILO
> (first in, last out). When an exception is raised by the __enter__()
> method, the right handed context managers are omitted.
> Grammar
> =======
> I'm not sure if I got the grammar right but I *think* the new grammar
> should look like::
> with_stmt: 'with' with_vars ':' suite
> with_var: test ['as' expr]
> with_vars: with_var (',' with_var)* [',']

I am sympathetic to this desire -- I think we almost added this to the
original PEP but decided to hold off until a clear need was found.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-ideas mailing list