[IPython-user] Controlling ipython prompt behavior

Walter Dörwald walter at livinglogic.de
Wed Jun 14 15:31:32 CDT 2006

Robert Kern wrote:

> Tom Denniston wrote:
>> When you hit enter at an Ipython prompt it prints out the repr of the
>> results of evaluating the line.  Is there a way to override this
>> behavior to control what gets done.  I could change the reprs on all
>> my objects but that is not a great solution.
> Yes. You can provide a 'result_display' function as a hook. I'm not sure what
> the best way to access hooks is, but something like the following should work:
> from IPython.genutils import Term
> from IPython.hooks import result_display
> def my_result_display(self, arg):
>     """ Yes, self is needed here.
>     See result_display() in IPython/hooks.py
>     """
>     if type(arg) is MySpecialType:
>         print >>Term.cout, arg.special_repr()
>     else:
>         # Fall back on the default behaviour.
>         result_display(self, arg)
>     return None

You can fall back to the next hook in the chain by raising ipapi.TryNext.

> # Is there a better way to get the InteractiveShell instance besides __IP?
> __IP.set_hook('result_display', my_result_display)

from IPython import ipapi
ipapi.get().set_hook("result_display", my_result_display)

> AFAICT, this *overrides* the current hook (unless if there is one of greater
> priority, see InteractiveShell.set_hook() in IPython/iplib.py), so be sure that
> your function can handle anything.


More information about the IPython-user mailing list