[Python-ideas] with statement: multiple context manager

Gregory P. Smith greg at krypto.org
Sun Mar 1 22:01:47 CET 2009


On Sun, Mar 1, 2009 at 11:46 AM, Guido van Rossum <guido at python.org> wrote:

> 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())
>

Alternatively if closer conformity with for loop syntax is desirable
consider this:

with lock, open(infile), open(outfile) as lock, fin, fout:
    fout.fwrite(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/)
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20090301/7dfd1989/attachment.html>


More information about the Python-ideas mailing list