##// END OF EJS Templates
Mostly final version of display data....
Mostly final version of display data. * New publish_display_data function. * backend_inline is using publish_display_data. * Documentation added.

File last commit:

r3225:a4af5739
r3277:aba5f629
Show More
formatters.py
169 lines | 5.2 KiB | text/x-python | PythonLexer
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 # -*- coding: utf-8 -*-
"""Displayhook formatters.
Robert Kern
BUG: formatting.
r3212 The DefaultFormatter is always present and may be configured from the
ipython_config.py file. For example, to add a pretty-printer for a numpy.dtype
object::
Robert Kern
ENH: Documentation for configuring the DefaultFormatter.
r3211
def dtype_pprinter(obj, p, cycle):
if cycle:
return p.text('dtype(...)')
if hasattr(obj, 'fields'):
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, '])')
c.DefaultFormatter.deferred_pprinters = {
('numpy', 'dtype'): dtype_pprinter,
}
The deferred_pprinters dictionary is the preferred way to configure these
pretty-printers. This allows you to define the pretty-printer without needing to
import the type itself. The dictionary maps (modulename, typename) pairs to
a function.
See the `IPython.external.pretty` documentation for how to write
pretty-printer functions.
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 """
Robert Kern
DOC: Add copyright comments.
r3225 #-----------------------------------------------------------------------------
# Copyright (c) 2010, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Robert Kern
BUG: Format according to the coding standard.
r3222 # Stdlib imports
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 import abc
from cStringIO import StringIO
Robert Kern
BUG: Format according to the coding standard.
r3222 # Our own imports
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 from IPython.config.configurable import Configurable
from IPython.external import pretty
from IPython.utils.traitlets import Bool, Dict, Int, Str
Robert Kern
BUG: Format according to the coding standard.
r3222 #-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 class DefaultFormatter(Configurable):
""" The default pretty-printer.
"""
# The ID of the formatter.
id = Str('default')
# The kind of data returned.
Robert Kern
ENH: Use text/plain for the format string of the DefaultFormatter....
r3214 # This is often, but not always a MIME type.
format = Str('text/plain')
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
# Whether to pretty-print or not.
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 pprint = Bool(True, config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
# Whether to be verbose or not.
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 verbose = Bool(False, config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
# The maximum width.
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 max_width = Int(79, config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
# The newline character.
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 newline = Str('\n', config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
# The singleton prettyprinters.
# Maps the IDs of the builtin singleton objects to the format functions.
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 singleton_pprinters = Dict(config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 def _singleton_pprinters_default(self):
return pretty._singleton_pprinters.copy()
# The type-specific prettyprinters.
# Map type objects to the format functions.
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 type_pprinters = Dict(config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 def _type_pprinters_default(self):
return pretty._type_pprinters.copy()
# The deferred-import type-specific prettyprinters.
# Map (modulename, classname) pairs to the format functions.
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 deferred_pprinters = Dict(config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 def _deferred_pprinters_default(self):
return pretty._deferred_type_pprinters.copy()
#### FormatterABC interface ####
def __call__(self, obj):
""" Format the object.
"""
if not self.pprint:
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 try:
return repr(obj)
except TypeError:
return ''
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 else:
stream = StringIO()
printer = pretty.RepresentationPrinter(stream, self.verbose,
self.max_width, self.newline,
singleton_pprinters=self.singleton_pprinters,
type_pprinters=self.type_pprinters,
deferred_pprinters=self.deferred_pprinters)
printer.pretty(obj)
printer.flush()
return stream.getvalue()
#### DefaultFormatter interface ####
def for_type(self, typ, func):
"""
Add a pretty printer for a given type.
"""
oldfunc = self.type_pprinters.get(typ, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore
# Nones.
self.type_pprinters[typ] = func
return oldfunc
def for_type_by_name(self, type_module, type_name, func):
"""
Add a pretty printer for a type specified by the module and name of
a type rather than the type object itself.
"""
key = (type_module, type_name)
oldfunc = self.deferred_pprinters.get(key, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore
# Nones.
self.deferred_pprinters[key] = func
return oldfunc
class FormatterABC(object):
""" Abstract base class for Formatters.
"""
__metaclass__ = abc.ABCMeta
# The ID of the formatter.
id = 'abstract'
# The kind of data returned.
Robert Kern
ENH: Use text/plain for the format string of the DefaultFormatter....
r3214 format = 'text/plain'
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
@abc.abstractmethod
def __call__(self, obj):
""" Return a JSONable representation of the object.
Robert Kern
ENH: Use text/plain for the format string of the DefaultFormatter....
r3214
If the object cannot be formatted by this formatter, then return None
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 """
Robert Kern
ENH: Use text/plain for the format string of the DefaultFormatter....
r3214 try:
return repr(obj)
except TypeError:
return None
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
FormatterABC.register(DefaultFormatter)