##// END OF EJS Templates
Missing imports
Missing imports

File last commit:

r11064:3bd12729
r11385:0a3b6c59
Show More
formatters.py
655 lines | 22.4 KiB | text/x-python | PythonLexer
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 # -*- coding: utf-8 -*-
Brian Granger
Display system is fully working now....
r3278 """Display formatters.
Thomas Kluyver
Only include inheritance diagram where it's useful.
r8795 Inheritance diagram:
.. inheritance-diagram:: IPython.core.formatters
:parts: 3
Brian Granger
Display system is fully working now....
r3278
Authors:
* Robert Kern
* Brian Granger
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 """
Robert Kern
DOC: Add copyright comments.
r3225 #-----------------------------------------------------------------------------
Matthias BUSSONNIER
update copyright to 2011/20xx-2011...
r5390 # Copyright (C) 2010-2011, IPython Development Team.
Robert Kern
DOC: Add copyright comments.
r3225 #
# 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
Brian Granger
More improvements to the display system....
r3279 #-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
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
MinRK
reorder stdlib imports...
r3352 import sys
MinRK
add missing warnings import
r9813 import warnings
Brian Granger
Display system is fully working now....
r3278 # We must use StringIO, as cStringIO doesn't handle unicode properly.
from StringIO import StringIO
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
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
Thomas Spura
Move pretty into lib, because it's heavily changed now.
r3413 from IPython.lib import pretty
MinRK
add DisplayFormatter.active_types...
r9811 from IPython.utils.traitlets import (
Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
)
Thomas Kluyver
More Python 3 compatibility fixes in core.
r4745 from IPython.utils.py3compat import unicode_to_str
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Robert Kern
BUG: Format according to the coding standard.
r3222 #-----------------------------------------------------------------------------
Brian Granger
Display system is fully working now....
r3278 # The main DisplayFormatter class
Robert Kern
BUG: Format according to the coding standard.
r3222 #-----------------------------------------------------------------------------
Brian Granger
Display system is fully working now....
r3278
class DisplayFormatter(Configurable):
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 # When set to true only the default plain text formatter will be used.
plain_text_only = Bool(False, config=True)
MinRK
add DisplayFormatter.active_types...
r9811 def _plain_text_only_changed(self, name, old, new):
warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
Use DisplayFormatter.active_types = ['text/plain']
for the same effect.
""", DeprecationWarning)
if new:
self.active_types = ['text/plain']
else:
self.active_types = self.format_types
active_types = List(Unicode, config=True,
MinRK
expand active_types help string
r10182 help="""List of currently active mime-types to display.
You can use this to set a white-list for formats to display.
Most users will not need to change this value.
""")
MinRK
add DisplayFormatter.active_types...
r9811 def _active_types_default(self):
return self.format_types
MinRK
implement active_types via formatter.enabled attributes...
r10128
def _active_types_changed(self, name, old, new):
MinRK
use items, not keys, duh
r10130 for key, formatter in self.formatters.items():
MinRK
implement active_types via formatter.enabled attributes...
r10128 if key in new:
formatter.enabled = True
else:
formatter.enabled = False
Brian Granger
Display system is fully working now....
r3278 # A dict of formatter whose keys are format types (MIME types) and whose
# values are subclasses of BaseFormatter.
MinRK
DisplayFormatter.formatters should not be configurable...
r5228 formatters = Dict()
Brian Granger
Display system is fully working now....
r3278 def _formatters_default(self):
"""Activate the default formatters."""
formatter_classes = [
PlainTextFormatter,
HTMLFormatter,
SVGFormatter,
PNGFormatter,
Brian E. Granger
Finishing display system work....
r4528 JPEGFormatter,
Brian Granger
Display system is fully working now....
r3278 LatexFormatter,
Brian Granger
Renaming the special methods of the formatters....
r3878 JSONFormatter,
JavascriptFormatter
Brian Granger
Display system is fully working now....
r3278 ]
d = {}
for cls in formatter_classes:
MinRK
use `parent=self` throughout IPython...
r11064 f = cls(parent=self)
Brian Granger
Display system is fully working now....
r3278 d[f.format_type] = f
return d
def format(self, obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
Brian E. Granger
Updates to the display system....
r4526 * application/javascript
Brian Granger
Display system is fully working now....
r3278 * image/png
Brian E. Granger
Finishing display system work....
r4528 * image/jpeg
Brian E. Granger
Updates to the display system....
r4526 * image/svg+xml
Brian Granger
Display system is fully working now....
r3278
Parameters
----------
obj : object
The Python object whose format data will be computed.
Brian Granger
Fixed docstring in formatter.py.
r3282 include : list or tuple, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list or tuple, optional
MinRK
add DisplayFormatter.active_types...
r9811 A list of format type string (MIME types) to exclude in the format
Brian Granger
Fixed docstring in formatter.py.
r3282 data dict. If this is set all format types will be computed,
except for those included in this argument.
Brian Granger
Display system is fully working now....
r3278
Returns
-------
MinRK
format-related docstrings!
r10446 (format_dict, metadata_dict) : tuple of two dicts
format_dict is a dictionary of key/value pairs, one of each format that was
Brian Granger
Display system is fully working now....
r3278 generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
MinRK
format-related docstrings!
r10446
metadata_dict is a dictionary of metadata about each mime-type output.
Its keys will be a strict subset of the keys in format_dict.
Brian Granger
Display system is fully working now....
r3278 """
format_dict = {}
MinRK
allow formatters to publish metadata...
r10443 md_dict = {}
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280
Brian Granger
Display system is fully working now....
r3278 for format_type, formatter in self.formatters.items():
MinRK
simplify include/exclude conditions
r10129 if include and format_type not in include:
continue
if exclude and format_type in exclude:
MinRK
add DisplayFormatter.active_types...
r9811 continue
MinRK
allow formatters to publish metadata...
r10443
md = None
Brian Granger
Display system is fully working now....
r3278 try:
data = formatter(obj)
except:
# FIXME: log the exception
raise
MinRK
allow formatters to publish metadata...
r10443
# formatters can return raw data or (data, metadata)
if isinstance(data, tuple) and len(data) == 2:
data, md = data
Brian Granger
Display system is fully working now....
r3278 if data is not None:
format_dict[format_type] = data
MinRK
allow formatters to publish metadata...
r10443 if md is not None:
md_dict[format_type] = md
return format_dict, md_dict
Brian Granger
Display system is fully working now....
r3278
@property
def format_types(self):
"""Return the format types (MIME types) of the active formatters."""
return self.formatters.keys()
#-----------------------------------------------------------------------------
# Formatters for specific format types (text, html, svg, etc.)
#-----------------------------------------------------------------------------
class FormatterABC(object):
""" Abstract base class for Formatters.
A formatter is a callable class that is responsible for computing the
raw format data for a particular format type (MIME type). For example,
an HTML formatter would have a format type of `text/html` and would return
the HTML representation of the object when called.
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 """
Brian Granger
Display system is fully working now....
r3278 __metaclass__ = abc.ABCMeta
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Brian Granger
Display system is fully working now....
r3278 # The format type of the data returned, usually a MIME type.
format_type = 'text/plain'
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 # Is the formatter enabled...
enabled = True
Brian Granger
Display system is fully working now....
r3278 @abc.abstractmethod
def __call__(self, obj):
"""Return a JSON'able representation of the object.
If the object cannot be formatted by this formatter, then return None
"""
try:
return repr(obj)
except TypeError:
return None
class BaseFormatter(Configurable):
"""A base formatter class that is configurable.
This formatter should usually be used as the base class of all formatters.
It is a traited :class:`Configurable` class and includes an extensible
API for users to determine how their objects are formatted. The following
logic is used to find a function to format an given object.
1. The object is introspected to see if it has a method with the name
:attr:`print_method`. If is does, that object is passed to that method
for formatting.
2. If no print method is found, three internal dictionaries are consulted
to find print method: :attr:`singleton_printers`, :attr:`type_printers`
and :attr:`deferred_printers`.
Brian Granger
Final work on display system....
r3288 Users should use these dictionaries to register functions that will be
used to compute the format data for their objects (if those objects don't
have the special print methods). The easiest way of using these
dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
methods.
Brian Granger
Display system is fully working now....
r3278
If no function/callable is found to compute the format data, ``None`` is
returned and this format type is not used.
"""
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('text/plain')
Brian Granger
Display system is fully working now....
r3278
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 enabled = Bool(True, config=True)
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('__repr__')
Brian Granger
Display system is fully working now....
r3278
# The singleton printers.
# Maps the IDs of the builtin singleton objects to the format functions.
singleton_printers = Dict(config=True)
def _singleton_printers_default(self):
return {}
# The type-specific printers.
# Map type objects to the format functions.
type_printers = Dict(config=True)
def _type_printers_default(self):
return {}
# The deferred-import type-specific printers.
# Map (modulename, classname) pairs to the format functions.
deferred_printers = Dict(config=True)
def _deferred_printers_default(self):
return {}
def __call__(self, obj):
"""Compute the format for an object."""
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 if self.enabled:
obj_id = id(obj)
Brian Granger
Display system is fully working now....
r3278 try:
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 obj_class = getattr(obj, '__class__', None) or type(obj)
Brian Granger
Renaming the special methods of the formatters....
r3878 # First try to find registered singleton printers for the type.
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 try:
printer = self.singleton_printers[obj_id]
except (TypeError, KeyError):
pass
Brian Granger
Display system is fully working now....
r3278 else:
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 return printer(obj)
Brian Granger
Renaming the special methods of the formatters....
r3878 # Next look for type_printers.
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 for cls in pretty._get_mro(obj_class):
if cls in self.type_printers:
return self.type_printers[cls](obj)
else:
printer = self._in_deferred_types(cls)
if printer is not None:
return printer(obj)
Brian Granger
Renaming the special methods of the formatters....
r3878 # Finally look for special method names.
if hasattr(obj_class, self.print_method):
printer = getattr(obj_class, self.print_method)
return printer(obj)
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 return None
except Exception:
pass
else:
Brian Granger
Display system is fully working now....
r3278 return None
def for_type(self, typ, func):
"""Add a format function for a given type.
Brian Granger
Final work on display system....
r3288 Parameters
Brian Granger
Display system is fully working now....
r3278 -----------
typ : class
The class of the object that will be formatted using `func`.
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument.
"""
oldfunc = self.type_printers.get(typ, None)
if func is not None:
# To support easy restoration of old printers, we need to ignore
# Nones.
self.type_printers[typ] = func
return oldfunc
def for_type_by_name(self, type_module, type_name, func):
"""Add a format function for a type specified by the full dotted
module and name of the type, rather than the type of the object.
Parameters
----------
type_module : str
The full dotted name of the module the type is defined in, like
``numpy``.
type_name : str
The name of the type (the class name), like ``dtype``
func : callable
The callable that will be called to compute the format data. The
call signature of this function is simple, it must take the
object to be formatted and return the raw data for the given
format. Subclasses may use a different call signature for the
`func` argument.
"""
key = (type_module, type_name)
oldfunc = self.deferred_printers.get(key, None)
if func is not None:
# To support easy restoration of old printers, we need to ignore
# Nones.
self.deferred_printers[key] = func
return oldfunc
Brian Granger
More improvements to the display system....
r3279 def _in_deferred_types(self, cls):
"""
Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use.
"""
mod = getattr(cls, '__module__', None)
name = getattr(cls, '__name__', None)
key = (mod, name)
printer = None
if key in self.deferred_printers:
# Move the printer over to the regular registry.
printer = self.deferred_printers.pop(key)
self.type_printers[cls] = printer
return printer
Brian Granger
Display system is fully working now....
r3278
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280
Brian Granger
Display system is fully working now....
r3278 class PlainTextFormatter(BaseFormatter):
"""The default pretty-printer.
Robert Kern
DOC: Fix references to IPython.lib.pretty instead of the old location IPython.external.pretty
r6292 This uses :mod:`IPython.lib.pretty` to compute the format data of
Brian Granger
Display system is fully working now....
r3278 the object. If the object cannot be pretty printed, :func:`repr` is used.
Robert Kern
DOC: Fix references to IPython.lib.pretty instead of the old location IPython.external.pretty
r6292 See the documentation of :mod:`IPython.lib.pretty` for details on
Brian Granger
Display system is fully working now....
r3278 how to write pretty printers. Here is a simple example::
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, '])')
"""
# The format type of data returned.
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('text/plain')
Brian Granger
Display system is fully working now....
r3278
Brian Granger
Lots of work on the display system, focused on pylab stuff....
r3280 # This subclass ignores this attribute as it always need to return
# something.
enabled = Bool(True, config=False)
Brian Granger
Renamed __pretty__ to _repr_pretty_ and changed updated pretty.py...
r3879 # Look for a _repr_pretty_ methods to use for pretty printing.
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('_repr_pretty_')
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.
MinRK
add Integer traitlet...
r5344 max_width = Integer(79, config=True)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
# The newline character.
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 newline = Unicode('\n', config=True)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 # format-string for pprinting floats
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 float_format = Unicode('%r')
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 # setter for float precision, either int or direct format-string
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 float_precision = CUnicode('', config=True)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 def _float_precision_changed(self, name, old, new):
"""float_precision changed, set float_format accordingly.
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 float_precision can be set by int or str.
This will set float_format, after interpreting input.
If numpy has been imported, numpy print precision will also be set.
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 integer `n` sets format to '%.nf', otherwise, format set directly.
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 An empty string returns to defaults (repr for float, 8 for numpy).
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 This parameter can be set via the '%precision' magic.
"""
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 if '%' in new:
# got explicit format string
fmt = new
try:
fmt%3.14159
except Exception:
raise ValueError("Precision must be int or format string, not %r"%new)
elif new:
# otherwise, should be an int
try:
i = int(new)
assert i >= 0
except ValueError:
raise ValueError("Precision must be int or format string, not %r"%new)
except AssertionError:
raise ValueError("int precision must be non-negative, not %r"%i)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 fmt = '%%.%if'%i
if 'numpy' in sys.modules:
# set numpy precision if it has been imported
import numpy
numpy.set_printoptions(precision=i)
else:
# default back to repr
fmt = '%r'
if 'numpy' in sys.modules:
import numpy
# numpy default is 8
numpy.set_printoptions(precision=8)
self.float_format = fmt
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Robert Kern
DOC: Fix references to IPython.lib.pretty instead of the old location IPython.external.pretty
r6292 # Use the default pretty printers from IPython.lib.pretty.
Brian Granger
Display system is fully working now....
r3278 def _singleton_printers_default(self):
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 return pretty._singleton_pprinters.copy()
Brian Granger
Display system is fully working now....
r3278 def _type_printers_default(self):
MinRK
add `float_precision` trait to PlainTextFormatter...
r3350 d = pretty._type_pprinters.copy()
d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
return d
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Brian Granger
Display system is fully working now....
r3278 def _deferred_printers_default(self):
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 return pretty._deferred_type_pprinters.copy()
#### FormatterABC interface ####
def __call__(self, obj):
Brian Granger
Display system is fully working now....
r3278 """Compute the pretty representation of the object."""
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 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:
Brian Granger
Display system is fully working now....
r3278 # This uses use StringIO, as cStringIO doesn't handle unicode.
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 stream = StringIO()
Thomas Kluyver
Comment explaining fix for gh-597.
r4373 # self.newline.encode() is a quick fix for issue gh-597. We need to
# ensure that stream does not get a mix of unicode and bytestrings,
# or it will cause trouble.
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 printer = pretty.RepresentationPrinter(stream, self.verbose,
Thomas Kluyver
More Python 3 compatibility fixes in core.
r4745 self.max_width, unicode_to_str(self.newline),
Brian Granger
Display system is fully working now....
r3278 singleton_pprinters=self.singleton_printers,
type_pprinters=self.type_printers,
deferred_pprinters=self.deferred_printers)
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 printer.pretty(obj)
printer.flush()
return stream.getvalue()
Brian Granger
Display system is fully working now....
r3278 class HTMLFormatter(BaseFormatter):
"""An HTML formatter.
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Brian Granger
Display system is fully working now....
r3278 To define the callables that compute the HTML representation of your
Brian Granger
Renaming the special methods of the formatters....
r3878 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
Brian Granger
Display system is fully working now....
r3278 or :meth:`for_type_by_name` methods to register functions that handle
this.
Brian Granger
Misc updates the display system....
r3880
The return value of this formatter should be a valid HTML snippet that
Bernardo B. Marques
remove all trailling spaces
r4872 could be injected into an existing DOM. It should *not* include the
Brian Granger
Misc updates the display system....
r3880 ```<html>`` or ```<body>`` tags.
Brian Granger
Display system is fully working now....
r3278 """
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('text/html')
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('_repr_html_')
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Brian Granger
Display system is fully working now....
r3278 class SVGFormatter(BaseFormatter):
"""An SVG formatter.
To define the callables that compute the SVG representation of your
Brian Granger
Renaming the special methods of the formatters....
r3878 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
Brian Granger
Display system is fully working now....
r3278 or :meth:`for_type_by_name` methods to register functions that handle
this.
Brian Granger
Misc updates the display system....
r3880
The return value of this formatter should be valid SVG enclosed in
```<svg>``` tags, that could be injected into an existing DOM. It should
*not* include the ```<html>`` or ```<body>`` tags.
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209 """
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('image/svg+xml')
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('_repr_svg_')
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Brian Granger
Display system is fully working now....
r3278 class PNGFormatter(BaseFormatter):
"""A PNG formatter.
Robert Kern
ENH: Use text/plain for the format string of the DefaultFormatter....
r3214
Brian Granger
Display system is fully working now....
r3278 To define the callables that compute the PNG representation of your
Brian Granger
Renaming the special methods of the formatters....
r3878 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
Brian Granger
Display system is fully working now....
r3278 or :meth:`for_type_by_name` methods to register functions that handle
Brian Granger
Renaming the special methods of the formatters....
r3878 this.
Brian Granger
Misc updates the display system....
r3880 The return value of this formatter should be raw PNG data, *not*
base64 encoded.
Brian Granger
Display system is fully working now....
r3278 """
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('image/png')
Brian Granger
Display system is fully working now....
r3278
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('_repr_png_')
Brian Granger
Display system is fully working now....
r3278
Brian E. Granger
Finishing display system work....
r4528 class JPEGFormatter(BaseFormatter):
"""A JPEG formatter.
To define the callables that compute the JPEG representation of your
objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
or :meth:`for_type_by_name` methods to register functions that handle
this.
The return value of this formatter should be raw JPEG data, *not*
base64 encoded.
"""
format_type = Unicode('image/jpeg')
print_method = ObjectName('_repr_jpeg_')
Brian Granger
Display system is fully working now....
r3278 class LatexFormatter(BaseFormatter):
"""A LaTeX formatter.
To define the callables that compute the LaTeX representation of your
Brian Granger
Renaming the special methods of the formatters....
r3878 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
Brian Granger
Display system is fully working now....
r3278 or :meth:`for_type_by_name` methods to register functions that handle
this.
Brian Granger
Misc updates the display system....
r3880
The return value of this formatter should be a valid LaTeX equation,
Brian Granger
Changes to Math class and added Latex class....
r6065 enclosed in either ```$```, ```$$``` or another LaTeX equation
environment.
Brian Granger
Display system is fully working now....
r3278 """
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('text/latex')
Brian Granger
Display system is fully working now....
r3278
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('_repr_latex_')
Brian Granger
Display system is fully working now....
r3278
class JSONFormatter(BaseFormatter):
"""A JSON string formatter.
To define the callables that compute the JSON string representation of
Brian Granger
Renaming the special methods of the formatters....
r3878 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
Brian Granger
Display system is fully working now....
r3278 or :meth:`for_type_by_name` methods to register functions that handle
this.
Brian Granger
Misc updates the display system....
r3880
The return value of this formatter should be a valid JSON string.
Brian Granger
Display system is fully working now....
r3278 """
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('application/json')
Brian Granger
Display system is fully working now....
r3278
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('_repr_json_')
Brian Granger
Renaming the special methods of the formatters....
r3878
class JavascriptFormatter(BaseFormatter):
"""A Javascript formatter.
To define the callables that compute the Javascript representation of
Bernardo B. Marques
remove all trailling spaces
r4872 your objects, define a :meth:`_repr_javascript_` method or use the
Brian Granger
Renaming the special methods of the formatters....
r3878 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
that handle this.
Brian Granger
Misc updates the display system....
r3880
The return value of this formatter should be valid Javascript code and
should *not* be enclosed in ```<script>``` tags.
Brian Granger
Renaming the special methods of the formatters....
r3878 """
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 format_type = Unicode('application/javascript')
Brian Granger
Display system is fully working now....
r3278
Thomas Kluyver
Add ObjectName and DottedObjectName trait types for referring to Python identifiers.
r4047 print_method = ObjectName('_repr_javascript_')
Brian Granger
Display system is fully working now....
r3278
FormatterABC.register(BaseFormatter)
FormatterABC.register(PlainTextFormatter)
FormatterABC.register(HTMLFormatter)
FormatterABC.register(SVGFormatter)
FormatterABC.register(PNGFormatter)
Brian E. Granger
Finishing display system work....
r4528 FormatterABC.register(JPEGFormatter)
Brian Granger
Display system is fully working now....
r3278 FormatterABC.register(LatexFormatter)
FormatterABC.register(JSONFormatter)
Brian Granger
Renaming the special methods of the formatters....
r3878 FormatterABC.register(JavascriptFormatter)
Brian Granger
Display system is fully working now....
r3278
def format_display_data(obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
The following MIME types are currently implemented:
* text/plain
* text/html
* text/latex
* application/json
Brian E. Granger
Updates to the display system....
r4526 * application/javascript
Brian Granger
Display system is fully working now....
r3278 * image/png
Brian E. Granger
Finishing display system work....
r4528 * image/jpeg
Brian E. Granger
Updates to the display system....
r4526 * image/svg+xml
Brian Granger
Display system is fully working now....
r3278
Parameters
----------
obj : object
The Python object whose format data will be computed.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
include : list or tuple, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list or tuple, optional
A list of format type string (MIME types) to exclue in the format
data dict. If this is set all format types will be computed,
except for those included in this argument.
"""
from IPython.core.interactiveshell import InteractiveShell
Robert Kern
ENH: Implement and test the default pretty formatter.
r3209
Brian Granger
Display system is fully working now....
r3278 InteractiveShell.instance().display_formatter.format(
obj,
include,
exclude
)
Brian E. Granger
Finishing display system work....
r4528