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

Brian Granger ellisonbg.net at gmail.com
Fri Sep 11 20:05:58 EDT 2009


Never mind this, I figured out it was a slightly different issue that was
causing the problem.

I *do* activate the displaytrap elsewhere, but my display trap context
manager
wasn't fully reentrant so the trap was being turned off in the wrong place
because of
a recursive call to __enter__:

with trap:
    # do something
    with trap:
        # do something else
    # Opps trap is off now!
    # All subsequence code doesn't have the trap set.

Moral of the story:  if your context managers can be entered recursively,
make sure
you have logic that prevents this type of thing.  It is easy logic to add
though.

Darren asks:

Can you do:
>
> with nested(self.builtin_trap, self.display_trap):
>     return fn(magic_args)
>

Maybe so, I am not sure what the ordering of the return vs __exit__ call is
in this case.
I will have to look this up.

Cheers,

Brian




On Fri, Sep 11, 2009 at 4:36 PM, Brian Granger <ellisonbg.net at 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?
>
> Cheers,
>
> Brian
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20090911/d60ec5e9/attachment.html>


More information about the IPython-dev mailing list