Skip to content

Commit 58f66e9

Browse files
committed
continue to use IPython for pretty-printing, but only if it is already loaded; never load it ourselves. Closes pydata#12.
1 parent ad06fc3 commit 58f66e9

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

patsy/util.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"SortAnythingKey",
1111
]
1212

13+
import sys
1314
import numpy as np
1415
from cStringIO import StringIO
1516
from compat import optional_dep_ok
@@ -381,13 +382,24 @@ def _mini_pretty(obj):
381382
printer.pretty(obj)
382383
return printer.getvalue()
383384

384-
if optional_dep_ok:
385-
try:
386-
from IPython.lib.pretty import pretty as repr_pretty_delegate
387-
except ImportError:
388-
repr_pretty_delegate = _mini_pretty
389-
else:
390-
repr_pretty_delegate = _mini_pretty
385+
def repr_pretty_delegate(obj):
386+
# If IPython is already loaded, then might as well use it. (Most commonly
387+
# this will occur if we are in an IPython session, but somehow someone has
388+
# called repr() directly. This can happen for example if printing an
389+
# container like a namedtuple that IPython lacks special code for
390+
# pretty-printing.) But, if IPython is not already imported, we do not
391+
# attempt to import it. This makes patsy itself faster to import (as of
392+
# Nov. 2012 I measured the extra overhead from loading IPython as ~4
393+
# seconds on a cold cache), it prevents IPython from automatically
394+
# spawning a bunch of child processes (!) which may not be what you want
395+
# if you are not otherwise using IPython, and it avoids annoying the
396+
# pandas people who have some hack to tell whether you are using IPython
397+
# in their test suite (see patsy bug #12).
398+
if optional_dep_ok and "IPython" in sys.modules:
399+
from IPython.lib.pretty import pretty
400+
return pretty(obj)
401+
else:
402+
return _mini_pretty(obj)
391403

392404
def repr_pretty_impl(p, obj, args, kwargs=[]):
393405
name = obj.__class__.__name__

0 commit comments

Comments
 (0)