[Python-ideas] revisit pep 377: good use case?
Michael Foord
fuzzyman at gmail.com
Wed Feb 29 15:24:30 CET 2012
On 29 February 2012 08:23, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On Wed, Feb 29, 2012 at 5:02 PM, Craig Yoshioka <craigyk at me.com> wrote:
> > PEP377 suggested some mechanics that seemed a bit complicated for
> getting the desired effect, but I think, and correct me if I'm wrong, that
> the same effect could be achieved by having the __enter__ function raise a
> StopIteration that would be caught by the context and skip directly to the
> __exit__ function.
>
> It was the overhead of doing exception handling around the __enter__
> call that got PEP 377 rejected.
>
> One way to handle this case is to use a separate if statement to make
> the flow control clear.
>
> with cm() as run_body:
> if run_body:
> # Do stuff
>
> Depending on the use case, the return value from __enter__ may be a
> simple flag as shown, or it may be a more complex object.
>
The trouble with this is it indents all your code an extra level. One
possibility would be allowing continue in a with statement as an early exit:
with cm() as run_body:
if not run_body:
continue
Michael
>
> Alternatively, you may want to investigate contextlib2, which aims to
> provide improved support for conditional cleanup in with statements.
> (in the current version, this is provided by contextlib2.ContextStack,
> but the next version will offer an improved API as
> contextlib2.CallbackStack. No current ETA on the next update though)
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
--
http://www.voidspace.org.uk/
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/20120229/329a348f/attachment.html>
More information about the Python-ideas
mailing list