[Python-ideas] revisit pep 377: good use case?

Craig Yoshioka craigyk at me.com
Wed Feb 29 20:44:01 CET 2012

Ok, I'll go clean them up to try and present them as concisely as possible.  The code to skip the with body would have to go in the __enter__ method because wether the body should be executed is dependent on the semantics of the context being used.  Imagine a context that looks like:

with uncached('file') as file:
    # write data to file

Making the context skippable only from __enter__ means the person writing the context can be more confident of the possible code paths.  And the person writing the body code could always just 'skip' manually anyways by returning early, i.e. per Michael's suggestion.

with uncached('file') as file:
    if not file: return

which isn't so bad, except it is overloading the meaning of file a bit, and why shouldn't the with block be skippable?

I can see a couple of ways it might work: 

1) catch raised StopIteration, or a new 'SkipWithBlock', exception thrown from the __enter__ code
2) skip the with block when __enter__ returns a unique value like SkipWithBlock, otherwise assign the returned value using 'as'

In my mind 2 should be easy? to implement, and shouldn't break any existing code since the new sentinel value didn't exist before anyways.  Maybe it would be more efficient that also wrapping __enter__ in yet another try|except|finally?

On Feb 29, 2012, at 11:29 AM, Ethan Furman wrote:

> Craig Yoshioka wrote:
>> I've tried classes, decorators, and passing the conditional using 'as', as suggested by Michael,  so I disagree that with is not suitable here since I have yet to find a better alternative.  If you want I can give pretty concrete examples in the ways they aren't as good.
> I would be interested in your concrete examples.
> As far as conditionally skipping the with body, where would that code go?  In __enter__?  How would it know whether or not to skip?
> ~Ethan~

More information about the Python-ideas mailing list