[docs] [issue32145] Wrong ExitStack Callback recipe

Barry A. Warsaw report at bugs.python.org
Fri Dec 29 10:03:31 EST 2017


Barry A. Warsaw <barry at python.org> added the comment:

On Dec 29, 2017, at 08:40, Nick Coghlan <report at bugs.python.org> wrote:
> 
> I'm not clear on what you mean about allowing arbitrary names for the instance creation function -

What I meant was that I don’t see `def _make_instance()` defined in your example, so I didn’t know if that was part of the contract between the base and derived classes, or an “arbitrary method” that subclasses can come up with.  From the example, it seems like the latter, but I could be misunderstanding your proposal.

> 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())

That’s actually not bad.  I think I like that better than the (IMHO, misnamed) _clone() API.  I’d quibble just a bit about the docstring, since the required API for target is exactly that it have a .callback() method that accepts a single exit callback argument.

----------

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


More information about the docs mailing list