From 72fe9b95f957a0e69c05563cbb25524c77c5f5e0 2014-01-12 22:20:51 From: MinRK Date: 2014-01-12 22:20:51 Subject: [PATCH] check return types of formatters and show error messages when formatters fail --- diff --git a/IPython/core/formatters.py b/IPython/core/formatters.py index a5a51a4..b948bbd 100644 --- a/IPython/core/formatters.py +++ b/IPython/core/formatters.py @@ -33,6 +33,7 @@ from IPython.external.decorator import decorator # Our own imports from IPython.config.configurable import Configurable from IPython.lib import pretty +from IPython.utils import io from IPython.utils.traitlets import ( Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, ) @@ -182,15 +183,21 @@ class DisplayFormatter(Configurable): # Formatters for specific format types (text, html, svg, etc.) #----------------------------------------------------------------------------- - @decorator def warn_format_error(method, self, *args, **kwargs): """decorator for warning on failed format call""" try: - return method(self, *args, **kwargs) + r = method(self, *args, **kwargs) except Exception as e: warn("Exception in %s formatter: %s" % (self.format_type, e)) return None + if r is None or isinstance(r, self._return_type): + return r + else: + warn("%s formatter returned invalid type %s for object: %s" % ( + self.format_type, type(r), pretty._safe_repr(obj) + )) + class FormatterABC(with_metaclass(abc.ABCMeta, object)): @@ -262,6 +269,7 @@ class BaseFormatter(Configurable): """ format_type = Unicode('text/plain') + _return_type = string_types enabled = Bool(True, config=True) @@ -278,7 +286,7 @@ class BaseFormatter(Configurable): # The deferred-import type-specific printers. # Map (modulename, classname) pairs to the format functions. deferred_printers = Dict(config=True) - + @warn_format_error def __call__(self, obj): """Compute the format for an object.""" @@ -679,6 +687,8 @@ class PNGFormatter(BaseFormatter): format_type = Unicode('image/png') print_method = ObjectName('_repr_png_') + + _return_type = bytes class JPEGFormatter(BaseFormatter): @@ -696,6 +706,8 @@ class JPEGFormatter(BaseFormatter): print_method = ObjectName('_repr_jpeg_') + _return_type = bytes + class LatexFormatter(BaseFormatter): """A LaTeX formatter.