diff --git a/IPython/core/builtin_trap.py b/IPython/core/builtin_trap.py
index f528dbb..ac59cae 100644
--- a/IPython/core/builtin_trap.py
+++ b/IPython/core/builtin_trap.py
@@ -61,7 +61,8 @@ class BuiltinTrap(Component):
if self._nested_level == 1:
self.unset()
self._nested_level -= 1
- return True
+ # Returning False will cause exceptions to propagate
+ return False
def add_builtin(self, key, value):
"""Add a builtin and save the original."""
diff --git a/IPython/core/display_trap.py b/IPython/core/display_trap.py
index 2f9fc3b..1628acc 100644
--- a/IPython/core/display_trap.py
+++ b/IPython/core/display_trap.py
@@ -62,7 +62,8 @@ class DisplayTrap(Component):
if self._nested_level == 1:
self.unset()
self._nested_level -= 1
- return True
+ # Returning False will cause exceptions to propagate
+ return False
def set(self):
"""Set the hook."""
diff --git a/IPython/core/iplib.py b/IPython/core/iplib.py
index 20eaaa4..cb6aa2c 100644
--- a/IPython/core/iplib.py
+++ b/IPython/core/iplib.py
@@ -1603,9 +1603,7 @@ class InteractiveShell(Component, Magic):
magic_args = self.var_expand(magic_args,1)
with nested(self.builtin_trap,):
result = fn(magic_args)
- # Unfortunately, the return statement is what will trigger
- # the displayhook, but it is no longer set!
- return result
+ return result
def define_magic(self, magicname, func):
"""Expose own function as magic function for ipython
@@ -2274,16 +2272,28 @@ class InteractiveShell(Component, Magic):
return lineout
#-------------------------------------------------------------------------
+ # Working with components
+ #-------------------------------------------------------------------------
+
+ def get_component(self, name=None, klass=None):
+ """Fetch a component by name and klass in my tree."""
+ c = Component.get_instances(root=self, name=name, klass=klass)
+ if len(c) == 1:
+ return c[0]
+ else:
+ return c
+
+ #-------------------------------------------------------------------------
# IPython extensions
#-------------------------------------------------------------------------
def load_extension(self, module_str):
- """Load an IPython extension.
+ """Load an IPython extension by its module name.
An IPython extension is an importable Python module that has
a function with the signature::
- def load_in_ipython(ipython):
+ def load_ipython_extension(ipython):
# Do things with ipython
This function is called after your extension is imported and the
@@ -2292,6 +2302,10 @@ class InteractiveShell(Component, Magic):
that point, including defining new magic and aliases, adding new
components, etc.
+ The :func:`load_ipython_extension` will be called again is you
+ load or reload the extension again. It is up to the extension
+ author to add code to manage that.
+
You can put your extension modules anywhere you want, as long as
they can be imported by Python's standard import mechanism. However,
to make it easy to write extensions, you can also put your extensions
@@ -2300,29 +2314,47 @@ class InteractiveShell(Component, Magic):
"""
from IPython.utils.syspathcontext import prepended_to_syspath
- if module_str in sys.modules:
- return
+ if module_str not in sys.modules:
+ with prepended_to_syspath(self.ipython_extension_dir):
+ __import__(module_str)
+ mod = sys.modules[module_str]
+ self._call_load_ipython_extension(mod)
- with prepended_to_syspath(self.ipython_extension_dir):
- __import__(module_str)
+ def unload_extension(self, module_str):
+ """Unload an IPython extension by its module name.
+
+ This function looks up the extension's name in ``sys.modules`` and
+ simply calls ``mod.unload_ipython_extension(self)``.
+ """
+ if module_str in sys.modules:
mod = sys.modules[module_str]
- self._call_load_in_ipython(mod)
+ self._call_unload_ipython_extension(mod)
def reload_extension(self, module_str):
- """Reload an IPython extension by doing reload."""
+ """Reload an IPython extension by calling reload.
+
+ If the module has not been loaded before,
+ :meth:`InteractiveShell.load_extension` is called. Otherwise
+ :func:`reload` is called and then the :func:`load_ipython_extension`
+ function of the module, if it exists is called.
+ """
from IPython.utils.syspathcontext import prepended_to_syspath
with prepended_to_syspath(self.ipython_extension_dir):
if module_str in sys.modules:
mod = sys.modules[module_str]
reload(mod)
- self._call_load_in_ipython(mod)
+ self._call_load_ipython_extension(mod)
else:
- self.load_extension(self, module_str)
+ self.load_extension(module_str)
+
+ def _call_load_ipython_extension(self, mod):
+ if hasattr(mod, 'load_ipython_extension'):
+ mod.load_ipython_extension(self)
- def _call_load_in_ipython(self, mod):
- if hasattr(mod, 'load_in_ipython'):
- mod.load_in_ipython(self)
+ def _call_unload_ipython_extension(self, mod):
+ if hasattr(mod, 'unload_ipython_extension'):
+ mod.unload_ipython_extension(self)
#-------------------------------------------------------------------------
# Things related to the prefilter
diff --git a/IPython/core/magic.py b/IPython/core/magic.py
index d06c9ab..32f822b 100644
--- a/IPython/core/magic.py
+++ b/IPython/core/magic.py
@@ -3538,5 +3538,16 @@ Defaulting color scheme to 'NoColor'"""
elif 'tk' in parameter_s:
return inputhook.enable_tk(app)
+ def magic_load_ext(self, module_str):
+ """Load an IPython extension by its module name."""
+ self.load_extension(module_str)
+
+ def magic_unload_ext(self, module_str):
+ """Unload an IPython extension by its module name."""
+ self.unload_extension(module_str)
+
+ def magic_reload_ext(self, module_str):
+ """Reload an IPython extension by its module name."""
+ self.reload_extension(module_str)
# end Magic
diff --git a/IPython/extensions/pretty.py b/IPython/extensions/pretty.py
new file mode 100644
index 0000000..d99cce9
--- /dev/null
+++ b/IPython/extensions/pretty.py
@@ -0,0 +1,193 @@
+"""Use pretty.py for configurable pretty-printing.
+
+To enable this extension in your configuration
+file, add the following to :file:`ipython_config.py`::
+
+ c.Global.extensions = ['IPython.extensions.pretty']
+ c.PrettyResultDisplay.verbose = True
+ c.PrettyResultDisplay.defaults = [
+ ('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')
+ ]
+
+This extension can also be loaded by using the ``%load_ext`` magic::
+
+ %load_ext IPython.extensions.pretty
+
+If this extension is enabled, you can always add additional pretty printers
+by doing::
+
+ ip = get_ipython()
+ prd = ip.get_component('pretty_result_display')
+ import numpy
+ from IPython.extensions.pretty import dtype_pprinter
+ prd.for_type(numpy.dtype, dtype_pprinter)
+
+ # If you don't want to have numpy imported until it needs to be:
+ prd.for_type_by_name('numpy', 'dtype', dtype_pprinter)
+"""
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+from IPython.core.error import TryNext
+from IPython.external import pretty
+from IPython.core.component import Component
+from IPython.utils.traitlets import Bool, List
+from IPython.utils.genutils import Term
+from IPython.utils.autoattr import auto_attr
+from IPython.utils.importstring import import_item
+
+#-----------------------------------------------------------------------------
+# Code
+#-----------------------------------------------------------------------------
+
+_loaded = False
+
+
+class PrettyResultDisplay(Component):
+
+ verbose = Bool(False, config=True)
+ # A list of (module_name, type_name, func_name), like
+ # [('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')]
+ defaults = List(default_value=[], config=True)
+
+ def __init__(self, parent, name=None, config=None):
+ super(PrettyResultDisplay, self).__init__(parent, name=name, config=config)
+ self.setup_defaults()
+
+ def setup_defaults(self):
+ """Initialize the default pretty printers."""
+ for type_module, type_name, func_name in self.defaults:
+ func = import_item(func_name)
+ self.for_type_by_name(type_module, type_name, func)
+
+ # Access other components like this rather than by regular attribute
+ # access.
+ @auto_attr
+ def shell(self):
+ return Component.get_instances(
+ root=self.root,
+ klass='IPython.core.iplib.InteractiveShell')[0]
+
+ def __call__(self, otherself, arg):
+ """Uber-pretty-printing display hook.
+
+ Called for displaying the result to the user.
+ """
+
+ if self.shell.pprint:
+ out = pretty.pretty(arg, verbose=self.verbose)
+ if '\n' in out:
+ # So that multi-line strings line up with the left column of
+ # the screen, instead of having the output prompt mess up
+ # their first line.
+ Term.cout.write('\n')
+ print >>Term.cout, out
+ else:
+ raise TryNext
+
+ def for_type(self, typ, func):
+ """Add a pretty printer for a type."""
+ return pretty.for_type(typ, func)
+
+ def for_type_by_name(self, type_module, type_name, func):
+ """Add a pretty printer for a type by its name and module name."""
+ print type_module, type_name, func
+ return pretty.for_type_by_name(type_name, type_name, func)
+
+
+#-----------------------------------------------------------------------------
+# Initialization code for the extension
+#-----------------------------------------------------------------------------
+
+
+def load_ipython_extension(ip):
+ global _loaded
+ if not _loaded:
+ prd = PrettyResultDisplay(ip, name='pretty_result_display')
+ ip.set_hook('result_display', prd, priority=99)
+ _loaded = True
+
+def unload_ipython_extension(ip):
+ # The hook system does not have a way to remove a hook so this is a pass
+ pass
+
+
+#-----------------------------------------------------------------------------
+# Example pretty printers
+#-----------------------------------------------------------------------------
+
+
+def dtype_pprinter(obj, p, cycle):
+ """ A pretty-printer for numpy dtype objects.
+ """
+ if cycle:
+ return p.text('dtype(...)')
+ if obj.fields is None:
+ p.text(repr(obj))
+ else:
+ p.begin_group(7, 'dtype([')
+ for i, field in enumerate(obj.descr):
+ if i > 0:
+ p.text(',')
+ p.breakable()
+ p.pretty(field)
+ p.end_group(7, '])')
+
+
+#-----------------------------------------------------------------------------
+# Tests
+#-----------------------------------------------------------------------------
+
+
+def test_pretty():
+ """
+ In [1]: from IPython.extensions import ipy_pretty
+
+ In [2]: ipy_pretty.activate()
+
+ In [3]: class A(object):
+ ...: def __repr__(self):
+ ...: return 'A()'
+ ...:
+ ...:
+
+ In [4]: a = A()
+
+ In [5]: a
+ Out[5]: A()
+
+ In [6]: def a_pretty_printer(obj, p, cycle):
+ ...: p.text('')
+ ...:
+ ...:
+
+ In [7]: ipy_pretty.for_type(A, a_pretty_printer)
+
+ In [8]: a
+ Out[8]:
+
+ In [9]: class B(object):
+ ...: def __repr__(self):
+ ...: return 'B()'
+ ...:
+ ...:
+
+ In [10]: B.__module__, B.__name__
+ Out[10]: ('__main__', 'B')
+
+ In [11]: def b_pretty_printer(obj, p, cycle):
+ ....: p.text('')
+ ....:
+ ....:
+
+ In [12]: ipy_pretty.for_type_by_name('__main__', 'B', b_pretty_printer)
+
+ In [13]: b = B()
+
+ In [14]: b
+ Out[14]:
+ """
+ assert False, "This should only be doctested, not run."
+
diff --git a/IPython/quarantine/ipy_pretty.py b/IPython/quarantine/ipy_pretty.py
deleted file mode 100644
index 1c6c977..0000000
--- a/IPython/quarantine/ipy_pretty.py
+++ /dev/null
@@ -1,133 +0,0 @@
-""" Use pretty.py for configurable pretty-printing.
-
-Register pretty-printers for types using ipy_pretty.for_type() or
-ipy_pretty.for_type_by_name(). For example, to use the example pretty-printer
-for numpy dtype objects, add the following to your ipy_user_conf.py::
-
- from IPython.extensions import ipy_pretty
-
- ipy_pretty.activate()
-
- # If you want to have numpy always imported anyways:
- import numpy
- ipy_pretty.for_type(numpy.dtype, ipy_pretty.dtype_pprinter)
-
- # If you don't want to have numpy imported until it needs to be:
- ipy_pretty.for_type_by_name('numpy', 'dtype', ipy_pretty.dtype_pprinter)
-"""
-
-from IPython.core import ipapi
-from IPython.core.error import TryNext
-from IPython.utils.genutils import Term
-
-from IPython.external import pretty
-
-ip = ipapi.get()
-
-
-#### Implementation ############################################################
-
-def pretty_result_display(self, arg):
- """ Uber-pretty-printing display hook.
-
- Called for displaying the result to the user.
- """
-
- if ip.options.pprint:
- verbose = getattr(ip.options, 'pretty_verbose', False)
- out = pretty.pretty(arg, verbose=verbose)
- if '\n' in out:
- # So that multi-line strings line up with the left column of
- # the screen, instead of having the output prompt mess up
- # their first line.
- Term.cout.write('\n')
- print >>Term.cout, out
- else:
- raise TryNext
-
-
-#### API #######################################################################
-
-# Expose the for_type and for_type_by_name functions for easier use.
-for_type = pretty.for_type
-for_type_by_name = pretty.for_type_by_name
-
-
-# FIXME: write deactivate(). We need a way to remove a hook.
-def activate():
- """ Activate this extension.
- """
- ip.set_hook('result_display', pretty_result_display, priority=99)
-
-
-#### Example pretty-printers ###################################################
-
-def dtype_pprinter(obj, p, cycle):
- """ A pretty-printer for numpy dtype objects.
- """
- if cycle:
- return p.text('dtype(...)')
- if obj.fields is None:
- p.text(repr(obj))
- else:
- p.begin_group(7, 'dtype([')
- for i, field in enumerate(obj.descr):
- if i > 0:
- p.text(',')
- p.breakable()
- p.pretty(field)
- p.end_group(7, '])')
-
-
-#### Tests #####################################################################
-
-def test_pretty():
- """
- In [1]: from IPython.extensions import ipy_pretty
-
- In [2]: ipy_pretty.activate()
-
- In [3]: class A(object):
- ...: def __repr__(self):
- ...: return 'A()'
- ...:
- ...:
-
- In [4]: a = A()
-
- In [5]: a
- Out[5]: A()
-
- In [6]: def a_pretty_printer(obj, p, cycle):
- ...: p.text('')
- ...:
- ...:
-
- In [7]: ipy_pretty.for_type(A, a_pretty_printer)
-
- In [8]: a
- Out[8]:
-
- In [9]: class B(object):
- ...: def __repr__(self):
- ...: return 'B()'
- ...:
- ...:
-
- In [10]: B.__module__, B.__name__
- Out[10]: ('__main__', 'B')
-
- In [11]: def b_pretty_printer(obj, p, cycle):
- ....: p.text('')
- ....:
- ....:
-
- In [12]: ipy_pretty.for_type_by_name('__main__', 'B', b_pretty_printer)
-
- In [13]: b = B()
-
- In [14]: b
- Out[14]:
- """
- assert False, "This should only be doctested, not run."
-
diff --git a/docs/source/config/ipython.txt b/docs/source/config/ipython.txt
index cf0a670..2b36017 100644
--- a/docs/source/config/ipython.txt
+++ b/docs/source/config/ipython.txt
@@ -54,15 +54,17 @@ the following attributes can be set in the ``Global`` section.
:attr:`c.Global.extensions`
A list of strings, each of which is an importable IPython extension. An
IPython extension is a regular Python module or package that has a
- :func:`load_in_ipython(ip)` method. This method gets called when the
- extension is loaded with the currently running
+ :func:`load_ipython_extension(ip)` method. This method gets called when
+ the extension is loaded with the currently running
:class:`~IPython.core.iplib.InteractiveShell` as its only argument. You
can put your extensions anywhere they can be imported but we add the
:file:`extensions` subdirectory of the ipython directory to ``sys.path``
- during extension loading, so you can put them there as well. Extensions
- are not executed in the user's interactive namespace and they must
- be pure Python code. Extensions are the recommended way of customizing
- :command:`ipython`.
+ during extension loading, so you can put them there as well. Extensions
+ are not executed in the user's interactive namespace and they must be pure
+ Python code. Extensions are the recommended way of customizing
+ :command:`ipython`. Extensions can provide an
+ :func:`unload_ipython_extension` that will be called when the extension is
+ unloaded.
:attr:`c.Global.exec_lines`
A list of strings, each of which is Python code that is run in the user's