<br><br><div class="gmail_quote">On 29 February 2012 08:23, Nick Coghlan <span dir="ltr"><<a href="mailto:ncoghlan@gmail.com">ncoghlan@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">On Wed, Feb 29, 2012 at 5:02 PM, Craig Yoshioka <<a href="mailto:craigyk@me.com">craigyk@me.com</a>> wrote:<br>
> 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.<br>

<br>
</div>It was the overhead of doing exception handling around the __enter__<br>
call that got PEP 377 rejected.<br>
<br>
One way to handle this case is to use a separate if statement to make<br>
the flow control clear.<br>
<br>
    with cm() as run_body:<br>
        if run_body:<br>
            # Do stuff<br>
<br>
Depending on the use case, the return value from __enter__ may be a<br>
simple flag as shown, or it may be a more complex object.<br></blockquote><div><br><br><br>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:<br>
<br>
    with cm() as run_body:<br>
        if not run_body:<br>
            continue<br><br>Michael<br>
<br><br> </div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
<br>
Alternatively, you may want to investigate contextlib2, which aims to<br>
provide improved support for conditional cleanup in with statements.<br>
(in the current version, this is provided by contextlib2.ContextStack,<br>
but the next version will offer an improved API as<br>
contextlib2.CallbackStack. No current ETA on the next update though)<br>
<br>
Cheers,<br>
Nick.<br>
<span class="HOEnZb"><font color="#888888"><br>
--<br>
Nick Coghlan   |   <a href="mailto:ncoghlan@gmail.com">ncoghlan@gmail.com</a>   |   Brisbane, Australia<br>
</font></span><div class="HOEnZb"><div class="h5">_______________________________________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org">Python-ideas@python.org</a><br>
<a href="http://mail.python.org/mailman/listinfo/python-ideas" target="_blank">http://mail.python.org/mailman/listinfo/python-ideas</a><br>
</div></div></blockquote></div><br><br clear="all"><br>-- <br><pre cols="72"><a href="http://www.voidspace.org.uk/" target="_blank">http://www.voidspace.org.uk/</a><br><br>May you do good and not evil<br>May you find forgiveness for yourself and forgive others<br>
May you share freely, never taking more than you give.<br>-- the sqlite blessing <a href="http://www.sqlite.org/different.html" target="_blank">http://www.sqlite.org/different.html</a></pre>
<br>