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

Nick Coghlan ncoghlan at gmail.com
Wed Feb 29 09:23:39 CET 2012

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.

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)


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list