[IPython-dev] Chasing my tail with the "with" statement

Darren Dale dsdale24@gmail....
Fri Sep 11 19:03:29 CDT 2009

On Fri, Sep 11, 2009 at 7:36 PM, Brian Granger <ellisonbg.net@gmail.com> wrote:
> Hi,
> I am converting some of the traps in IPython to use the with statement.  The
> idea is that
> things like sys.excepthook, sys.displayhook, etc. are not always set by
> IPython,
> but only when user code is actually being run.  But, I am running into a
> problem
> with sys.displayhook with the results of a magic function.
> The prefilter machinery converts:
> %alias -> get_ipython().magic("alias")
> The end of the get_ipython().magic function looks like this:
>             with nested(self.builtin_trap, self.display_trap):
>                 result = fn(magic_args)
>             return result
> This idea is that we use "with" to enable the display_trap, call the
> magic and then return the result.  The builtin_trap works fine, but
> the display_trap doesn't work.  The problem is that sys.displaytrap
> is only called when something is returned.  But by then ("return result")
> the "with" block has ended and the display_trap is deactivated.
> There are other places that I can enable the display_trap, but we
> loose the nice feature of only having the trap set when it is needed.
> Any ideas of how we can get around having to leave display_trap set
> all the time?

Can you do:

with nested(self.builtin_trap, self.display_trap):
    return fn(magic_args)


More information about the IPython-dev mailing list