Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/IPython/core/formatters.py: 39%
362 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1# -*- coding: utf-8 -*-
2"""Display formatters.
4Inheritance diagram:
6.. inheritance-diagram:: IPython.core.formatters
7 :parts: 3
8"""
10# Copyright (c) IPython Development Team.
11# Distributed under the terms of the Modified BSD License.
13import abc
14import sys
15import traceback
16import warnings
17from io import StringIO
19from decorator import decorator
21from traitlets.config.configurable import Configurable
22from .getipython import get_ipython
23from ..utils.sentinel import Sentinel
24from ..utils.dir2 import get_real_method
25from ..lib import pretty
26from traitlets import (
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 ForwardDeclaredInstance,
29 default, observe,
30)
32from typing import Any
35class DisplayFormatter(Configurable):
37 active_types = List(Unicode(),
38 help="""List of currently active mime-types to display.
39 You can use this to set a white-list for formats to display.
41 Most users will not need to change this value.
42 """).tag(config=True)
44 @default('active_types')
45 def _active_types_default(self):
46 return self.format_types
48 @observe('active_types')
49 def _active_types_changed(self, change):
50 for key, formatter in self.formatters.items():
51 if key in change['new']:
52 formatter.enabled = True
53 else:
54 formatter.enabled = False
56 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
57 @default('ipython_display_formatter')
58 def _default_formatter(self):
59 return IPythonDisplayFormatter(parent=self)
61 mimebundle_formatter = ForwardDeclaredInstance('FormatterABC')
62 @default('mimebundle_formatter')
63 def _default_mime_formatter(self):
64 return MimeBundleFormatter(parent=self)
66 # A dict of formatter whose keys are format types (MIME types) and whose
67 # values are subclasses of BaseFormatter.
68 formatters = Dict()
69 @default('formatters')
70 def _formatters_default(self):
71 """Activate the default formatters."""
72 formatter_classes = [
73 PlainTextFormatter,
74 HTMLFormatter,
75 MarkdownFormatter,
76 SVGFormatter,
77 PNGFormatter,
78 PDFFormatter,
79 JPEGFormatter,
80 LatexFormatter,
81 JSONFormatter,
82 JavascriptFormatter
83 ]
84 d = {}
85 for cls in formatter_classes:
86 f = cls(parent=self)
87 d[f.format_type] = f
88 return d
90 def format(self, obj, include=None, exclude=None):
91 """Return a format data dict for an object.
93 By default all format types will be computed.
95 The following MIME types are usually implemented:
97 * text/plain
98 * text/html
99 * text/markdown
100 * text/latex
101 * application/json
102 * application/javascript
103 * application/pdf
104 * image/png
105 * image/jpeg
106 * image/svg+xml
108 Parameters
109 ----------
110 obj : object
111 The Python object whose format data will be computed.
112 include : list, tuple or set; optional
113 A list of format type strings (MIME types) to include in the
114 format data dict. If this is set *only* the format types included
115 in this list will be computed.
116 exclude : list, tuple or set; optional
117 A list of format type string (MIME types) to exclude in the format
118 data dict. If this is set all format types will be computed,
119 except for those included in this argument.
120 Mimetypes present in exclude will take precedence over the ones in include
122 Returns
123 -------
124 (format_dict, metadata_dict) : tuple of two dicts
125 format_dict is a dictionary of key/value pairs, one of each format that was
126 generated for the object. The keys are the format types, which
127 will usually be MIME type strings and the values and JSON'able
128 data structure containing the raw data for the representation in
129 that format.
131 metadata_dict is a dictionary of metadata about each mime-type output.
132 Its keys will be a strict subset of the keys in format_dict.
134 Notes
135 -----
136 If an object implement `_repr_mimebundle_` as well as various
137 `_repr_*_`, the data returned by `_repr_mimebundle_` will take
138 precedence and the corresponding `_repr_*_` for this mimetype will
139 not be called.
141 """
142 format_dict = {}
143 md_dict = {}
145 if self.ipython_display_formatter(obj):
146 # object handled itself, don't proceed
147 return {}, {}
149 format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude)
151 if format_dict or md_dict:
152 if include:
153 format_dict = {k:v for k,v in format_dict.items() if k in include}
154 md_dict = {k:v for k,v in md_dict.items() if k in include}
155 if exclude:
156 format_dict = {k:v for k,v in format_dict.items() if k not in exclude}
157 md_dict = {k:v for k,v in md_dict.items() if k not in exclude}
159 for format_type, formatter in self.formatters.items():
160 if format_type in format_dict:
161 # already got it from mimebundle, maybe don't render again.
162 # exception: manually registered per-mime renderer
163 # check priority:
164 # 1. user-registered per-mime formatter
165 # 2. mime-bundle (user-registered or repr method)
166 # 3. default per-mime formatter (e.g. repr method)
167 try:
168 formatter.lookup(obj)
169 except KeyError:
170 # no special formatter, use mime-bundle-provided value
171 continue
172 if include and format_type not in include:
173 continue
174 if exclude and format_type in exclude:
175 continue
177 md = None
178 try:
179 data = formatter(obj)
180 except:
181 # FIXME: log the exception
182 raise
184 # formatters can return raw data or (data, metadata)
185 if isinstance(data, tuple) and len(data) == 2:
186 data, md = data
188 if data is not None:
189 format_dict[format_type] = data
190 if md is not None:
191 md_dict[format_type] = md
192 return format_dict, md_dict
194 @property
195 def format_types(self):
196 """Return the format types (MIME types) of the active formatters."""
197 return list(self.formatters.keys())
200#-----------------------------------------------------------------------------
201# Formatters for specific format types (text, html, svg, etc.)
202#-----------------------------------------------------------------------------
205def _safe_repr(obj):
206 """Try to return a repr of an object
208 always returns a string, at least.
209 """
210 try:
211 return repr(obj)
212 except Exception as e:
213 return "un-repr-able object (%r)" % e
216class FormatterWarning(UserWarning):
217 """Warning class for errors in formatters"""
219@decorator
220def catch_format_error(method, self, *args, **kwargs):
221 """show traceback on failed format call"""
222 try:
223 r = method(self, *args, **kwargs)
224 except NotImplementedError:
225 # don't warn on NotImplementedErrors
226 return self._check_return(None, args[0])
227 except Exception:
228 exc_info = sys.exc_info()
229 ip = get_ipython()
230 if ip is not None:
231 ip.showtraceback(exc_info)
232 else:
233 traceback.print_exception(*exc_info)
234 return self._check_return(None, args[0])
235 return self._check_return(r, args[0])
238class FormatterABC(metaclass=abc.ABCMeta):
239 """ Abstract base class for Formatters.
241 A formatter is a callable class that is responsible for computing the
242 raw format data for a particular format type (MIME type). For example,
243 an HTML formatter would have a format type of `text/html` and would return
244 the HTML representation of the object when called.
245 """
247 # The format type of the data returned, usually a MIME type.
248 format_type = 'text/plain'
250 # Is the formatter enabled...
251 enabled = True
253 @abc.abstractmethod
254 def __call__(self, obj):
255 """Return a JSON'able representation of the object.
257 If the object cannot be formatted by this formatter,
258 warn and return None.
259 """
260 return repr(obj)
263def _mod_name_key(typ):
264 """Return a (__module__, __name__) tuple for a type.
266 Used as key in Formatter.deferred_printers.
267 """
268 module = getattr(typ, '__module__', None)
269 name = getattr(typ, '__name__', None)
270 return (module, name)
273def _get_type(obj):
274 """Return the type of an instance (old and new-style)"""
275 return getattr(obj, '__class__', None) or type(obj)
278_raise_key_error = Sentinel('_raise_key_error', __name__,
279"""
280Special value to raise a KeyError
282Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
283""")
286class BaseFormatter(Configurable):
287 """A base formatter class that is configurable.
289 This formatter should usually be used as the base class of all formatters.
290 It is a traited :class:`Configurable` class and includes an extensible
291 API for users to determine how their objects are formatted. The following
292 logic is used to find a function to format an given object.
294 1. The object is introspected to see if it has a method with the name
295 :attr:`print_method`. If is does, that object is passed to that method
296 for formatting.
297 2. If no print method is found, three internal dictionaries are consulted
298 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
299 and :attr:`deferred_printers`.
301 Users should use these dictionaries to register functions that will be
302 used to compute the format data for their objects (if those objects don't
303 have the special print methods). The easiest way of using these
304 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
305 methods.
307 If no function/callable is found to compute the format data, ``None`` is
308 returned and this format type is not used.
309 """
311 format_type = Unicode("text/plain")
312 _return_type: Any = str
314 enabled = Bool(True).tag(config=True)
316 print_method = ObjectName('__repr__')
318 # The singleton printers.
319 # Maps the IDs of the builtin singleton objects to the format functions.
320 singleton_printers = Dict().tag(config=True)
322 # The type-specific printers.
323 # Map type objects to the format functions.
324 type_printers = Dict().tag(config=True)
326 # The deferred-import type-specific printers.
327 # Map (modulename, classname) pairs to the format functions.
328 deferred_printers = Dict().tag(config=True)
330 @catch_format_error
331 def __call__(self, obj):
332 """Compute the format for an object."""
333 if self.enabled:
334 # lookup registered printer
335 try:
336 printer = self.lookup(obj)
337 except KeyError:
338 pass
339 else:
340 return printer(obj)
341 # Finally look for special method names
342 method = get_real_method(obj, self.print_method)
343 if method is not None:
344 return method()
345 return None
346 else:
347 return None
349 def __contains__(self, typ):
350 """map in to lookup_by_type"""
351 try:
352 self.lookup_by_type(typ)
353 except KeyError:
354 return False
355 else:
356 return True
358 def _check_return(self, r, obj):
359 """Check that a return value is appropriate
361 Return the value if so, None otherwise, warning if invalid.
362 """
363 if r is None or isinstance(r, self._return_type) or \
364 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
365 return r
366 else:
367 warnings.warn(
368 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
369 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
370 FormatterWarning
371 )
373 def lookup(self, obj):
374 """Look up the formatter for a given instance.
376 Parameters
377 ----------
378 obj : object instance
380 Returns
381 -------
382 f : callable
383 The registered formatting callable for the type.
385 Raises
386 ------
387 KeyError if the type has not been registered.
388 """
389 # look for singleton first
390 obj_id = id(obj)
391 if obj_id in self.singleton_printers:
392 return self.singleton_printers[obj_id]
393 # then lookup by type
394 return self.lookup_by_type(_get_type(obj))
396 def lookup_by_type(self, typ):
397 """Look up the registered formatter for a type.
399 Parameters
400 ----------
401 typ : type or '__module__.__name__' string for a type
403 Returns
404 -------
405 f : callable
406 The registered formatting callable for the type.
408 Raises
409 ------
410 KeyError if the type has not been registered.
411 """
412 if isinstance(typ, str):
413 typ_key = tuple(typ.rsplit('.',1))
414 if typ_key not in self.deferred_printers:
415 # We may have it cached in the type map. We will have to
416 # iterate over all of the types to check.
417 for cls in self.type_printers:
418 if _mod_name_key(cls) == typ_key:
419 return self.type_printers[cls]
420 else:
421 return self.deferred_printers[typ_key]
422 else:
423 for cls in pretty._get_mro(typ):
424 if cls in self.type_printers or self._in_deferred_types(cls):
425 return self.type_printers[cls]
427 # If we have reached here, the lookup failed.
428 raise KeyError("No registered printer for {0!r}".format(typ))
430 def for_type(self, typ, func=None):
431 """Add a format function for a given type.
433 Parameters
434 ----------
435 typ : type or '__module__.__name__' string for a type
436 The class of the object that will be formatted using `func`.
438 func : callable
439 A callable for computing the format data.
440 `func` will be called with the object to be formatted,
441 and will return the raw data in this formatter's format.
442 Subclasses may use a different call signature for the
443 `func` argument.
445 If `func` is None or not specified, there will be no change,
446 only returning the current value.
448 Returns
449 -------
450 oldfunc : callable
451 The currently registered callable.
452 If you are registering a new formatter,
453 this will be the previous value (to enable restoring later).
454 """
455 # if string given, interpret as 'pkg.module.class_name'
456 if isinstance(typ, str):
457 type_module, type_name = typ.rsplit('.', 1)
458 return self.for_type_by_name(type_module, type_name, func)
460 try:
461 oldfunc = self.lookup_by_type(typ)
462 except KeyError:
463 oldfunc = None
465 if func is not None:
466 self.type_printers[typ] = func
468 return oldfunc
470 def for_type_by_name(self, type_module, type_name, func=None):
471 """Add a format function for a type specified by the full dotted
472 module and name of the type, rather than the type of the object.
474 Parameters
475 ----------
476 type_module : str
477 The full dotted name of the module the type is defined in, like
478 ``numpy``.
480 type_name : str
481 The name of the type (the class name), like ``dtype``
483 func : callable
484 A callable for computing the format data.
485 `func` will be called with the object to be formatted,
486 and will return the raw data in this formatter's format.
487 Subclasses may use a different call signature for the
488 `func` argument.
490 If `func` is None or unspecified, there will be no change,
491 only returning the current value.
493 Returns
494 -------
495 oldfunc : callable
496 The currently registered callable.
497 If you are registering a new formatter,
498 this will be the previous value (to enable restoring later).
499 """
500 key = (type_module, type_name)
502 try:
503 oldfunc = self.lookup_by_type("%s.%s" % key)
504 except KeyError:
505 oldfunc = None
507 if func is not None:
508 self.deferred_printers[key] = func
509 return oldfunc
511 def pop(self, typ, default=_raise_key_error):
512 """Pop a formatter for the given type.
514 Parameters
515 ----------
516 typ : type or '__module__.__name__' string for a type
517 default : object
518 value to be returned if no formatter is registered for typ.
520 Returns
521 -------
522 obj : object
523 The last registered object for the type.
525 Raises
526 ------
527 KeyError if the type is not registered and default is not specified.
528 """
530 if isinstance(typ, str):
531 typ_key = tuple(typ.rsplit('.',1))
532 if typ_key not in self.deferred_printers:
533 # We may have it cached in the type map. We will have to
534 # iterate over all of the types to check.
535 for cls in self.type_printers:
536 if _mod_name_key(cls) == typ_key:
537 old = self.type_printers.pop(cls)
538 break
539 else:
540 old = default
541 else:
542 old = self.deferred_printers.pop(typ_key)
543 else:
544 if typ in self.type_printers:
545 old = self.type_printers.pop(typ)
546 else:
547 old = self.deferred_printers.pop(_mod_name_key(typ), default)
548 if old is _raise_key_error:
549 raise KeyError("No registered value for {0!r}".format(typ))
550 return old
552 def _in_deferred_types(self, cls):
553 """
554 Check if the given class is specified in the deferred type registry.
556 Successful matches will be moved to the regular type registry for future use.
557 """
558 mod = getattr(cls, '__module__', None)
559 name = getattr(cls, '__name__', None)
560 key = (mod, name)
561 if key in self.deferred_printers:
562 # Move the printer over to the regular registry.
563 printer = self.deferred_printers.pop(key)
564 self.type_printers[cls] = printer
565 return True
566 return False
569class PlainTextFormatter(BaseFormatter):
570 """The default pretty-printer.
572 This uses :mod:`IPython.lib.pretty` to compute the format data of
573 the object. If the object cannot be pretty printed, :func:`repr` is used.
574 See the documentation of :mod:`IPython.lib.pretty` for details on
575 how to write pretty printers. Here is a simple example::
577 def dtype_pprinter(obj, p, cycle):
578 if cycle:
579 return p.text('dtype(...)')
580 if hasattr(obj, 'fields'):
581 if obj.fields is None:
582 p.text(repr(obj))
583 else:
584 p.begin_group(7, 'dtype([')
585 for i, field in enumerate(obj.descr):
586 if i > 0:
587 p.text(',')
588 p.breakable()
589 p.pretty(field)
590 p.end_group(7, '])')
591 """
593 # The format type of data returned.
594 format_type = Unicode('text/plain')
596 # This subclass ignores this attribute as it always need to return
597 # something.
598 enabled = Bool(True).tag(config=False)
600 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
601 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
603 Set to 0 to disable truncation.
604 """
605 ).tag(config=True)
607 # Look for a _repr_pretty_ methods to use for pretty printing.
608 print_method = ObjectName('_repr_pretty_')
610 # Whether to pretty-print or not.
611 pprint = Bool(True).tag(config=True)
613 # Whether to be verbose or not.
614 verbose = Bool(False).tag(config=True)
616 # The maximum width.
617 max_width = Integer(79).tag(config=True)
619 # The newline character.
620 newline = Unicode('\n').tag(config=True)
622 # format-string for pprinting floats
623 float_format = Unicode('%r')
624 # setter for float precision, either int or direct format-string
625 float_precision = CUnicode('').tag(config=True)
627 @observe('float_precision')
628 def _float_precision_changed(self, change):
629 """float_precision changed, set float_format accordingly.
631 float_precision can be set by int or str.
632 This will set float_format, after interpreting input.
633 If numpy has been imported, numpy print precision will also be set.
635 integer `n` sets format to '%.nf', otherwise, format set directly.
637 An empty string returns to defaults (repr for float, 8 for numpy).
639 This parameter can be set via the '%precision' magic.
640 """
641 new = change['new']
642 if '%' in new:
643 # got explicit format string
644 fmt = new
645 try:
646 fmt%3.14159
647 except Exception as e:
648 raise ValueError("Precision must be int or format string, not %r"%new) from e
649 elif new:
650 # otherwise, should be an int
651 try:
652 i = int(new)
653 assert i >= 0
654 except ValueError as e:
655 raise ValueError("Precision must be int or format string, not %r"%new) from e
656 except AssertionError as e:
657 raise ValueError("int precision must be non-negative, not %r"%i) from e
659 fmt = '%%.%if'%i
660 if 'numpy' in sys.modules:
661 # set numpy precision if it has been imported
662 import numpy
663 numpy.set_printoptions(precision=i)
664 else:
665 # default back to repr
666 fmt = '%r'
667 if 'numpy' in sys.modules:
668 import numpy
669 # numpy default is 8
670 numpy.set_printoptions(precision=8)
671 self.float_format = fmt
673 # Use the default pretty printers from IPython.lib.pretty.
674 @default('singleton_printers')
675 def _singleton_printers_default(self):
676 return pretty._singleton_pprinters.copy()
678 @default('type_printers')
679 def _type_printers_default(self):
680 d = pretty._type_pprinters.copy()
681 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
682 # if NumPy is used, set precision for its float64 type
683 if "numpy" in sys.modules:
684 import numpy
686 d[numpy.float64] = lambda obj, p, cycle: p.text(self.float_format % obj)
687 return d
689 @default('deferred_printers')
690 def _deferred_printers_default(self):
691 return pretty._deferred_type_pprinters.copy()
693 #### FormatterABC interface ####
695 @catch_format_error
696 def __call__(self, obj):
697 """Compute the pretty representation of the object."""
698 if not self.pprint:
699 return repr(obj)
700 else:
701 stream = StringIO()
702 printer = pretty.RepresentationPrinter(stream, self.verbose,
703 self.max_width, self.newline,
704 max_seq_length=self.max_seq_length,
705 singleton_pprinters=self.singleton_printers,
706 type_pprinters=self.type_printers,
707 deferred_pprinters=self.deferred_printers)
708 printer.pretty(obj)
709 printer.flush()
710 return stream.getvalue()
713class HTMLFormatter(BaseFormatter):
714 """An HTML formatter.
716 To define the callables that compute the HTML representation of your
717 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
718 or :meth:`for_type_by_name` methods to register functions that handle
719 this.
721 The return value of this formatter should be a valid HTML snippet that
722 could be injected into an existing DOM. It should *not* include the
723 ```<html>`` or ```<body>`` tags.
724 """
725 format_type = Unicode('text/html')
727 print_method = ObjectName('_repr_html_')
730class MarkdownFormatter(BaseFormatter):
731 """A Markdown formatter.
733 To define the callables that compute the Markdown representation of your
734 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
735 or :meth:`for_type_by_name` methods to register functions that handle
736 this.
738 The return value of this formatter should be a valid Markdown.
739 """
740 format_type = Unicode('text/markdown')
742 print_method = ObjectName('_repr_markdown_')
744class SVGFormatter(BaseFormatter):
745 """An SVG formatter.
747 To define the callables that compute the SVG representation of your
748 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
749 or :meth:`for_type_by_name` methods to register functions that handle
750 this.
752 The return value of this formatter should be valid SVG enclosed in
753 ```<svg>``` tags, that could be injected into an existing DOM. It should
754 *not* include the ```<html>`` or ```<body>`` tags.
755 """
756 format_type = Unicode('image/svg+xml')
758 print_method = ObjectName('_repr_svg_')
761class PNGFormatter(BaseFormatter):
762 """A PNG formatter.
764 To define the callables that compute the PNG representation of your
765 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
766 or :meth:`for_type_by_name` methods to register functions that handle
767 this.
769 The return value of this formatter should be raw PNG data, *not*
770 base64 encoded.
771 """
772 format_type = Unicode('image/png')
774 print_method = ObjectName('_repr_png_')
776 _return_type = (bytes, str)
779class JPEGFormatter(BaseFormatter):
780 """A JPEG formatter.
782 To define the callables that compute the JPEG representation of your
783 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
784 or :meth:`for_type_by_name` methods to register functions that handle
785 this.
787 The return value of this formatter should be raw JPEG data, *not*
788 base64 encoded.
789 """
790 format_type = Unicode('image/jpeg')
792 print_method = ObjectName('_repr_jpeg_')
794 _return_type = (bytes, str)
797class LatexFormatter(BaseFormatter):
798 """A LaTeX formatter.
800 To define the callables that compute the LaTeX representation of your
801 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
802 or :meth:`for_type_by_name` methods to register functions that handle
803 this.
805 The return value of this formatter should be a valid LaTeX equation,
806 enclosed in either ```$```, ```$$``` or another LaTeX equation
807 environment.
808 """
809 format_type = Unicode('text/latex')
811 print_method = ObjectName('_repr_latex_')
814class JSONFormatter(BaseFormatter):
815 """A JSON string formatter.
817 To define the callables that compute the JSONable representation of
818 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
819 or :meth:`for_type_by_name` methods to register functions that handle
820 this.
822 The return value of this formatter should be a JSONable list or dict.
823 JSON scalars (None, number, string) are not allowed, only dict or list containers.
824 """
825 format_type = Unicode('application/json')
826 _return_type = (list, dict)
828 print_method = ObjectName('_repr_json_')
830 def _check_return(self, r, obj):
831 """Check that a return value is appropriate
833 Return the value if so, None otherwise, warning if invalid.
834 """
835 if r is None:
836 return
837 md = None
838 if isinstance(r, tuple):
839 # unpack data, metadata tuple for type checking on first element
840 r, md = r
842 assert not isinstance(
843 r, str
844 ), "JSON-as-string has been deprecated since IPython < 3"
846 if md is not None:
847 # put the tuple back together
848 r = (r, md)
849 return super(JSONFormatter, self)._check_return(r, obj)
852class JavascriptFormatter(BaseFormatter):
853 """A Javascript formatter.
855 To define the callables that compute the Javascript representation of
856 your objects, define a :meth:`_repr_javascript_` method or use the
857 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
858 that handle this.
860 The return value of this formatter should be valid Javascript code and
861 should *not* be enclosed in ```<script>``` tags.
862 """
863 format_type = Unicode('application/javascript')
865 print_method = ObjectName('_repr_javascript_')
868class PDFFormatter(BaseFormatter):
869 """A PDF formatter.
871 To define the callables that compute the PDF representation of your
872 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
873 or :meth:`for_type_by_name` methods to register functions that handle
874 this.
876 The return value of this formatter should be raw PDF data, *not*
877 base64 encoded.
878 """
879 format_type = Unicode('application/pdf')
881 print_method = ObjectName('_repr_pdf_')
883 _return_type = (bytes, str)
885class IPythonDisplayFormatter(BaseFormatter):
886 """An escape-hatch Formatter for objects that know how to display themselves.
888 To define the callables that compute the representation of your
889 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
890 or :meth:`for_type_by_name` methods to register functions that handle
891 this. Unlike mime-type displays, this method should not return anything,
892 instead calling any appropriate display methods itself.
894 This display formatter has highest priority.
895 If it fires, no other display formatter will be called.
897 Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types
898 without registering a new Formatter.
900 IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types,
901 so `_ipython_display_` should only be used for objects that require unusual
902 display patterns, such as multiple display calls.
903 """
904 print_method = ObjectName('_ipython_display_')
905 _return_type = (type(None), bool)
907 @catch_format_error
908 def __call__(self, obj):
909 """Compute the format for an object."""
910 if self.enabled:
911 # lookup registered printer
912 try:
913 printer = self.lookup(obj)
914 except KeyError:
915 pass
916 else:
917 printer(obj)
918 return True
919 # Finally look for special method names
920 method = get_real_method(obj, self.print_method)
921 if method is not None:
922 method()
923 return True
926class MimeBundleFormatter(BaseFormatter):
927 """A Formatter for arbitrary mime-types.
929 Unlike other `_repr_<mimetype>_` methods,
930 `_repr_mimebundle_` should return mime-bundle data,
931 either the mime-keyed `data` dictionary or the tuple `(data, metadata)`.
932 Any mime-type is valid.
934 To define the callables that compute the mime-bundle representation of your
935 objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type`
936 or :meth:`for_type_by_name` methods to register functions that handle
937 this.
939 .. versionadded:: 6.1
940 """
941 print_method = ObjectName('_repr_mimebundle_')
942 _return_type = dict
944 def _check_return(self, r, obj):
945 r = super(MimeBundleFormatter, self)._check_return(r, obj)
946 # always return (data, metadata):
947 if r is None:
948 return {}, {}
949 if not isinstance(r, tuple):
950 return r, {}
951 return r
953 @catch_format_error
954 def __call__(self, obj, include=None, exclude=None):
955 """Compute the format for an object.
957 Identical to parent's method but we pass extra parameters to the method.
959 Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in
960 particular `include` and `exclude`.
961 """
962 if self.enabled:
963 # lookup registered printer
964 try:
965 printer = self.lookup(obj)
966 except KeyError:
967 pass
968 else:
969 return printer(obj)
970 # Finally look for special method names
971 method = get_real_method(obj, self.print_method)
973 if method is not None:
974 return method(include=include, exclude=exclude)
975 return None
976 else:
977 return None
980FormatterABC.register(BaseFormatter)
981FormatterABC.register(PlainTextFormatter)
982FormatterABC.register(HTMLFormatter)
983FormatterABC.register(MarkdownFormatter)
984FormatterABC.register(SVGFormatter)
985FormatterABC.register(PNGFormatter)
986FormatterABC.register(PDFFormatter)
987FormatterABC.register(JPEGFormatter)
988FormatterABC.register(LatexFormatter)
989FormatterABC.register(JSONFormatter)
990FormatterABC.register(JavascriptFormatter)
991FormatterABC.register(IPythonDisplayFormatter)
992FormatterABC.register(MimeBundleFormatter)
995def format_display_data(obj, include=None, exclude=None):
996 """Return a format data dict for an object.
998 By default all format types will be computed.
1000 Parameters
1001 ----------
1002 obj : object
1003 The Python object whose format data will be computed.
1005 Returns
1006 -------
1007 format_dict : dict
1008 A dictionary of key/value pairs, one or each format that was
1009 generated for the object. The keys are the format types, which
1010 will usually be MIME type strings and the values and JSON'able
1011 data structure containing the raw data for the representation in
1012 that format.
1013 include : list or tuple, optional
1014 A list of format type strings (MIME types) to include in the
1015 format data dict. If this is set *only* the format types included
1016 in this list will be computed.
1017 exclude : list or tuple, optional
1018 A list of format type string (MIME types) to exclude in the format
1019 data dict. If this is set all format types will be computed,
1020 except for those included in this argument.
1021 """
1022 from .interactiveshell import InteractiveShell
1024 return InteractiveShell.instance().display_formatter.format(
1025 obj,
1026 include,
1027 exclude
1028 )