[New-bugs-announce] [issue45184] Add `pop` function to remove context manager from (Async)ExitStack
report at bugs.python.org
Mon Sep 13 10:40:02 EDT 2021
New submission from Andreas H. <ahangauer at gmx.net>:
Currently it is not possible to remove context managers from an ExitStack (or AsyncExitStack).
Workarounds are difficult and generally do accesses implementation details of (Async)ExitStack.
See e.g. https://stackoverflow.com/a/37607405. It could be done as follows:
"""Same as AsyncExitStack but with pop, i.e. removal functionality"""
async def pop(self, cm):
callbacks = self._exit_callbacks
self._exit_callbacks = collections.deque()
found = None
cb = callbacks.popleft()
if cb.__self__ == cm:
found = cb
if not found:
raise KeyError("context manager not found")
return await found(None, None, None)
The alternative is re-implementation of ExitStack with pop functionality, but that is also very difficult to get right (especially with exceptions). Which is probably the reason why there is ExitStack in the library at all.
So I propose to augment (Async)ExitStack with a `pop` method like above or similar to the above.
An example is a component that manages several connections to network services.
During run-time the network services might need to change (i.e. some be disconnected and some be connected according to business logic), or handle re-connection events (ie. graceful response to network errors).
It is not too hard to imagine more use cases.
Essentially every case where dynamic resource management is needed and where single resources are managable with python context managers.
components: Library (Lib)
nosy: andreash, ncoghlan, yselivanov
title: Add `pop` function to remove context manager from (Async)ExitStack
versions: Python 3.10, Python 3.11, Python 3.6, Python 3.7, Python 3.8, Python 3.9
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce