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