[Python-ideas] Fast context creation

Nick Coghlan ncoghlan at gmail.com
Thu Nov 27 15:29:54 CET 2014


On 27 November 2014 at 23:04, Akira Li <4kir4.1i at gmail.com> wrote:
> Stefano Borini <stefano.borini at ferrara.linux.it>
> writes:
>
>> I have a situation where, no matter how the routine ends, I need to return the focus to a widget. It would be
>> rather clever to do this with a context, but I would expect something like this to be a possible strategy
>>
>>     with contextlib.context(enter=None, exit=lambda *args: my_widget.setFocus()):
>>         do what I need to do
>>
>> as far as I know, at the moment it's not possible. Am I right? I think it would be an easy and practical
>> addition to the contextlib module to quickly register two routines for enter and exit.
>
>
>   with ExitStack() as stack:
>       stack.callback(my_widget.setFocus)
>       cm = stack.enter_context(run_your_enter_routine())
>
> https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack

Right, while the underlying try/except/finally construct is generally
a better option for simple cases of inline ad hoc exception handling,
ExitStack is useful when you really do want to reproduce the context
management protocols "pass the exception details to a callback"
behaviour. For example, the feature requested by the OP can be
implemented as:

    @contextmanager
    def context(enter=None, exit=None):
        enter_result = enter() if enter is not None else None
        with ExitStack() as stack:
            if exit is not None:
                stack.push(exit)
            yield enter_result

However, I'm hard pressed to think of a case where using such a
construct would be clearer than writing out a suitable
try/except/finally block. A lot of the value of context managers lies
in our ability to give them *names*, such that it's immediately clear
what they're doing (or which docs to look up to find out more).

Cheers,
Nick.

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


More information about the Python-ideas mailing list