[docs] [issue32145] Wrong ExitStack Callback recipe

Nick Coghlan report at bugs.python.org
Fri Dec 29 08:40:02 EST 2017


Nick Coghlan <ncoghlan at gmail.com> added the comment:

I'm not clear on what you mean about allowing arbitrary names for the instance creation function - at that point we're back to subclasses not being able to use the default `pop_all()` implementation at all, and needing to duplicate the state transfer logic in the subclass (which we don't provide a public API to do, since the `_exit_callbacks` queue is deliberately private).

However, I'm thinking we could potentially change `pop_all` *itself* to accept a target object:

    def pop_all(self, *, target=None):
        """Preserve the context stack by transferring it to a new instance

        If a *target* stack is given, it must be either an `ExitStack`
        instance, or else provide a callback registration method akin to `ExitStack.callback`.
        """
        if target is None:
            target = type(self)()
        exit_callbacks = self._exit_callbacks
        self._exit_callbacks = deque()
        if isinstance(target, ExitStack):
            target._exit_callbacks = exit_callbacks
        else:
            for cb in exit_callbacks:
                target.callback(cb)
        return target

The recipe fix would then be to make `Callback.cancel()` look like:

    def cancel(self):
        # We deliberately *don't* clean up the cancelled callback
        self.pop_all(target=ExitStack())

(Tangent: https://bugs.python.org/issue32445 suggests adding a small optimisation to `ExitStack.callback` to skip adding the wrapper when `args` and `kwds` are both empty)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32145>
_______________________________________


More information about the docs mailing list