[Python-ideas] Generator-based context managers can't skip __exit__

Nick Coghlan ncoghlan at gmail.com
Sun Nov 6 02:38:37 EST 2016


On 6 November 2016 at 17:18, Ram Rachum <ram at rachum.com> wrote:
> On Sun, Nov 6, 2016 at 8:53 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> There's still something seriously odd going in relation to your
>> overall resource management architecture if "cleanup, maybe, unless I
>> decide to tell you not to" is a behaviour you regularly need. Cleanup
>> functions in a garbage collected environment should be idempotent, so
>> it doesn't matter if you redundantly call them again later.
>
>
> Well, you think it's weird that I want a `finally` clause to not be called
> in some circumstances. Do you think it's equally weird to want an `__exit__`
> method that is not called in some circumstances?

Yes, as the whole point of __exit__ is that the interpreter goes to
great lengths to make sure it always gets called, no matter what else
happens with the currently executing frame (whether it finishes
normally, returns early, breaks out of a loop, continues with the next
iteration, raises an exception, or gets suspended without ever
resuming normal execution).

If you don't want that behaviour, then __exit__ likely isn't the right
tool (although it may provide the technical basis for a selective
cleanup framework).

Cheers,
Nick.

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


More information about the Python-ideas mailing list