[Python-ideas] Defer Statement

Nick Coghlan ncoghlan at gmail.com
Sun Jun 4 02:38:27 EDT 2017


On 3 June 2017 at 22:24, Nick Coghlan <ncoghlan at gmail.com> wrote:
> So while I'm definitely sympathetic to the use case (otherwise
> ExitStack wouldn't have a callback() method), "this would be useful"
> isn't a sufficient argument in this particular case - what's needed is
> a justification that this pattern of resource management is common
> enough to justify giving functions an optional implicit ExitStack
> instance and assigning a dedicated keyword for adding entries to it.

It occurred to me that I should elaborate a bit further here, and
point out explicitly that one of the main benefits of ExitStack (and,
indeed, the main reason it exists) is that it allows resource
lifecycle management to be deterministic, *without* necessarily tying
it to function calls or with statements.

The behave BDD test framework, for example, defines hooks that run
before and after each feature and scenario, as well as before and
after the entire test run. I use those to set up "scenario_cleanup",
"_feature_cleanup" and "_global_cleanup" stacks as part of the testing
context: https://github.com/leapp-to/prototype/blob/master/integration-tests/features/environment.py#L49

If a test step implementor allocates a resource that needs to be
cleaned up, they register it with "context.scenario_cleanup", and then
the "after scenario" hook takes care of closing the ExitStack instance
and cleaning everything up appropriately.

For me, that kind of situation is when I'm most inclined to reach for
ExitStack, whereas when the cleanup needs align with the function call
stack, I'm more likely to reach for contexlib.contextmanager or an
explicit try/finally.

Cheers,
Nick.

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


More information about the Python-ideas mailing list