[Python-ideas] Generator-based context managers can't skip __exit__
Nick Coghlan
ncoghlan at gmail.com
Sun Nov 6 23:11:22 EST 2016
On 7 November 2016 at 12:25, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 11/06/2016 12:44 AM, Ram Rachum wrote:
>
>> I see that Python does allow you to not call `__exit__` if you don't want
>> to [...]
>
> Um, how? I was unaware of this (mis-)feature.
It involves wrapping the context manager in another context manager
that deliberately doesn't delegate the call to __exit__ in some cases
(cf contextlib.ExitStack.pop_all()).
By contrast, if __del__ is defined (as it is on generators), if you
don't keep the context manager itself alive, you can only prevent the
cleanup happening if you can define a subclass to use instead, and
that's not always possible (deliberately so, in the case of generator
cleanup).
So the odd part of Ram's request isn't wanting to have conditional
resource cleanup - the recipes in the contextlib docs gives some
examples of where conditional local resource management is useful and
how to achieve it using ExitStack. The odd part is wanting to make the
resource cleanup implicitly unreliable, rather than having it be
reliable by default and folks having to explicitly opt in to disabling
it, since the easiest way to obtain non-deterministic resource
management is to just avoid using the context management features in
the first place.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list