[Python-ideas] with statement: multiple context manager

Christian Heimes lists at cheimes.de
Sun Mar 1 14:49:03 CET 2009

Hello fellow Pythonistas!

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.


The nested block::

  with lock:
      with open(infile) as fin:
          with open(outfile, 'w') as fout:

could be written as::

  with lock, open(infile) as fin, open(outfile, 'w') as fout:

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.


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)* [',']


More information about the Python-ideas mailing list