[Python-ideas] with *context_managers:

Michael Foord fuzzyman at gmail.com
Mon Apr 2 14:00:06 CEST 2012

On 2 April 2012 12:40, Giampaolo Rodolà <g.rodola at gmail.com> wrote:

> Il 01 aprile 2012 22:25, Ram Rachum <ram.rachum at gmail.com> ha scritto:
> > I'd like to be able to do this:
> >
> > with *context_managers:
> >     pass # Some suite.
> >
> >
> > This is useful when you have an unknown number of context managers that
> you
> > want to use. I currently use `contextlib.nested`, but I'd like the *star
> > syntax much better.
> >
> > What do you think?
> >
> >
> > Ram.
> I believe writing a specialized context manager object which is able
> to hold multiple context managers altogheter is better than
> introducing a new syntax for such a use case which should be pretty
> rare/uncommon.

There's now an example of a need for this in the standard library.
mock.patch collects together an arbitrary number of context managers that
need to be entered sequentially (together). As there is no replacement for
contextlib.nested it has custom code calling __enter__ and __exit__ on all
the context managers and keeping track of which ones have been successfully
entered (because if there is an exception whilst entering one, only those
that have *already* been entered should have __exit__ called).

> Also, it's not clear what to expect from "with *context_managers as ctx:
> ...".
It is clear. It should be a tuple of results (what else *could* it be).


> Regards,
> --- Giampaolo
> http://code.google.com/p/pyftpdlib/
> http://code.google.com/p/psutil/
> http://code.google.com/p/pysendfile/
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120402/591d6f75/attachment.html>

More information about the Python-ideas mailing list