formatters.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. # -*- coding: utf-8 -*-
  2. """Display formatters.
  3. Inheritance diagram:
  4. .. inheritance-diagram:: IPython.core.formatters
  5. :parts: 3
  6. """
  7. # Copyright (c) IPython Development Team.
  8. # Distributed under the terms of the Modified BSD License.
  9. import abc
  10. import json
  11. import sys
  12. import traceback
  13. import warnings
  14. from decorator import decorator
  15. from traitlets.config.configurable import Configurable
  16. from IPython.core.getipython import get_ipython
  17. from IPython.utils.sentinel import Sentinel
  18. from IPython.utils.dir2 import get_real_method
  19. from IPython.lib import pretty
  20. from traitlets import (
  21. Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
  22. ForwardDeclaredInstance,
  23. default, observe,
  24. )
  25. from IPython.utils.py3compat import (
  26. with_metaclass, string_types, unicode_type,
  27. )
  28. class DisplayFormatter(Configurable):
  29. active_types = List(Unicode(),
  30. help="""List of currently active mime-types to display.
  31. You can use this to set a white-list for formats to display.
  32. Most users will not need to change this value.
  33. """).tag(config=True)
  34. @default('active_types')
  35. def _active_types_default(self):
  36. return self.format_types
  37. @observe('active_types')
  38. def _active_types_changed(self, change):
  39. for key, formatter in self.formatters.items():
  40. if key in change['new']:
  41. formatter.enabled = True
  42. else:
  43. formatter.enabled = False
  44. ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
  45. @default('ipython_display_formatter')
  46. def _default_formatter(self):
  47. return IPythonDisplayFormatter(parent=self)
  48. # A dict of formatter whose keys are format types (MIME types) and whose
  49. # values are subclasses of BaseFormatter.
  50. formatters = Dict()
  51. @default('formatters')
  52. def _formatters_default(self):
  53. """Activate the default formatters."""
  54. formatter_classes = [
  55. PlainTextFormatter,
  56. HTMLFormatter,
  57. MarkdownFormatter,
  58. SVGFormatter,
  59. PNGFormatter,
  60. PDFFormatter,
  61. JPEGFormatter,
  62. LatexFormatter,
  63. JSONFormatter,
  64. JavascriptFormatter
  65. ]
  66. d = {}
  67. for cls in formatter_classes:
  68. f = cls(parent=self)
  69. d[f.format_type] = f
  70. return d
  71. def format(self, obj, include=None, exclude=None):
  72. """Return a format data dict for an object.
  73. By default all format types will be computed.
  74. The following MIME types are currently implemented:
  75. * text/plain
  76. * text/html
  77. * text/markdown
  78. * text/latex
  79. * application/json
  80. * application/javascript
  81. * application/pdf
  82. * image/png
  83. * image/jpeg
  84. * image/svg+xml
  85. Parameters
  86. ----------
  87. obj : object
  88. The Python object whose format data will be computed.
  89. include : list or tuple, optional
  90. A list of format type strings (MIME types) to include in the
  91. format data dict. If this is set *only* the format types included
  92. in this list will be computed.
  93. exclude : list or tuple, optional
  94. A list of format type string (MIME types) to exclude in the format
  95. data dict. If this is set all format types will be computed,
  96. except for those included in this argument.
  97. Returns
  98. -------
  99. (format_dict, metadata_dict) : tuple of two dicts
  100. format_dict is a dictionary of key/value pairs, one of each format that was
  101. generated for the object. The keys are the format types, which
  102. will usually be MIME type strings and the values and JSON'able
  103. data structure containing the raw data for the representation in
  104. that format.
  105. metadata_dict is a dictionary of metadata about each mime-type output.
  106. Its keys will be a strict subset of the keys in format_dict.
  107. """
  108. format_dict = {}
  109. md_dict = {}
  110. if self.ipython_display_formatter(obj):
  111. # object handled itself, don't proceed
  112. return {}, {}
  113. for format_type, formatter in self.formatters.items():
  114. if include and format_type not in include:
  115. continue
  116. if exclude and format_type in exclude:
  117. continue
  118. md = None
  119. try:
  120. data = formatter(obj)
  121. except:
  122. # FIXME: log the exception
  123. raise
  124. # formatters can return raw data or (data, metadata)
  125. if isinstance(data, tuple) and len(data) == 2:
  126. data, md = data
  127. if data is not None:
  128. format_dict[format_type] = data
  129. if md is not None:
  130. md_dict[format_type] = md
  131. return format_dict, md_dict
  132. @property
  133. def format_types(self):
  134. """Return the format types (MIME types) of the active formatters."""
  135. return list(self.formatters.keys())
  136. #-----------------------------------------------------------------------------
  137. # Formatters for specific format types (text, html, svg, etc.)
  138. #-----------------------------------------------------------------------------
  139. def _safe_repr(obj):
  140. """Try to return a repr of an object
  141. always returns a string, at least.
  142. """
  143. try:
  144. return repr(obj)
  145. except Exception as e:
  146. return "un-repr-able object (%r)" % e
  147. class FormatterWarning(UserWarning):
  148. """Warning class for errors in formatters"""
  149. @decorator
  150. def catch_format_error(method, self, *args, **kwargs):
  151. """show traceback on failed format call"""
  152. try:
  153. r = method(self, *args, **kwargs)
  154. except NotImplementedError:
  155. # don't warn on NotImplementedErrors
  156. return None
  157. except Exception:
  158. exc_info = sys.exc_info()
  159. ip = get_ipython()
  160. if ip is not None:
  161. ip.showtraceback(exc_info)
  162. else:
  163. traceback.print_exception(*exc_info)
  164. return None
  165. return self._check_return(r, args[0])
  166. class FormatterABC(with_metaclass(abc.ABCMeta, object)):
  167. """ Abstract base class for Formatters.
  168. A formatter is a callable class that is responsible for computing the
  169. raw format data for a particular format type (MIME type). For example,
  170. an HTML formatter would have a format type of `text/html` and would return
  171. the HTML representation of the object when called.
  172. """
  173. # The format type of the data returned, usually a MIME type.
  174. format_type = 'text/plain'
  175. # Is the formatter enabled...
  176. enabled = True
  177. @abc.abstractmethod
  178. def __call__(self, obj):
  179. """Return a JSON'able representation of the object.
  180. If the object cannot be formatted by this formatter,
  181. warn and return None.
  182. """
  183. return repr(obj)
  184. def _mod_name_key(typ):
  185. """Return a (__module__, __name__) tuple for a type.
  186. Used as key in Formatter.deferred_printers.
  187. """
  188. module = getattr(typ, '__module__', None)
  189. name = getattr(typ, '__name__', None)
  190. return (module, name)
  191. def _get_type(obj):
  192. """Return the type of an instance (old and new-style)"""
  193. return getattr(obj, '__class__', None) or type(obj)
  194. _raise_key_error = Sentinel('_raise_key_error', __name__,
  195. """
  196. Special value to raise a KeyError
  197. Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
  198. """)
  199. class BaseFormatter(Configurable):
  200. """A base formatter class that is configurable.
  201. This formatter should usually be used as the base class of all formatters.
  202. It is a traited :class:`Configurable` class and includes an extensible
  203. API for users to determine how their objects are formatted. The following
  204. logic is used to find a function to format an given object.
  205. 1. The object is introspected to see if it has a method with the name
  206. :attr:`print_method`. If is does, that object is passed to that method
  207. for formatting.
  208. 2. If no print method is found, three internal dictionaries are consulted
  209. to find print method: :attr:`singleton_printers`, :attr:`type_printers`
  210. and :attr:`deferred_printers`.
  211. Users should use these dictionaries to register functions that will be
  212. used to compute the format data for their objects (if those objects don't
  213. have the special print methods). The easiest way of using these
  214. dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
  215. methods.
  216. If no function/callable is found to compute the format data, ``None`` is
  217. returned and this format type is not used.
  218. """
  219. format_type = Unicode('text/plain')
  220. _return_type = string_types
  221. enabled = Bool(True).tag(config=True)
  222. print_method = ObjectName('__repr__')
  223. # The singleton printers.
  224. # Maps the IDs of the builtin singleton objects to the format functions.
  225. singleton_printers = Dict().tag(config=True)
  226. # The type-specific printers.
  227. # Map type objects to the format functions.
  228. type_printers = Dict().tag(config=True)
  229. # The deferred-import type-specific printers.
  230. # Map (modulename, classname) pairs to the format functions.
  231. deferred_printers = Dict().tag(config=True)
  232. @catch_format_error
  233. def __call__(self, obj):
  234. """Compute the format for an object."""
  235. if self.enabled:
  236. # lookup registered printer
  237. try:
  238. printer = self.lookup(obj)
  239. except KeyError:
  240. pass
  241. else:
  242. return printer(obj)
  243. # Finally look for special method names
  244. method = get_real_method(obj, self.print_method)
  245. if method is not None:
  246. return method()
  247. return None
  248. else:
  249. return None
  250. def __contains__(self, typ):
  251. """map in to lookup_by_type"""
  252. try:
  253. self.lookup_by_type(typ)
  254. except KeyError:
  255. return False
  256. else:
  257. return True
  258. def _check_return(self, r, obj):
  259. """Check that a return value is appropriate
  260. Return the value if so, None otherwise, warning if invalid.
  261. """
  262. if r is None or isinstance(r, self._return_type) or \
  263. (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
  264. return r
  265. else:
  266. warnings.warn(
  267. "%s formatter returned invalid type %s (expected %s) for object: %s" % \
  268. (self.format_type, type(r), self._return_type, _safe_repr(obj)),
  269. FormatterWarning
  270. )
  271. def lookup(self, obj):
  272. """Look up the formatter for a given instance.
  273. Parameters
  274. ----------
  275. obj : object instance
  276. Returns
  277. -------
  278. f : callable
  279. The registered formatting callable for the type.
  280. Raises
  281. ------
  282. KeyError if the type has not been registered.
  283. """
  284. # look for singleton first
  285. obj_id = id(obj)
  286. if obj_id in self.singleton_printers:
  287. return self.singleton_printers[obj_id]
  288. # then lookup by type
  289. return self.lookup_by_type(_get_type(obj))
  290. def lookup_by_type(self, typ):
  291. """Look up the registered formatter for a type.
  292. Parameters
  293. ----------
  294. typ : type or '__module__.__name__' string for a type
  295. Returns
  296. -------
  297. f : callable
  298. The registered formatting callable for the type.
  299. Raises
  300. ------
  301. KeyError if the type has not been registered.
  302. """
  303. if isinstance(typ, string_types):
  304. typ_key = tuple(typ.rsplit('.',1))
  305. if typ_key not in self.deferred_printers:
  306. # We may have it cached in the type map. We will have to
  307. # iterate over all of the types to check.
  308. for cls in self.type_printers:
  309. if _mod_name_key(cls) == typ_key:
  310. return self.type_printers[cls]
  311. else:
  312. return self.deferred_printers[typ_key]
  313. else:
  314. for cls in pretty._get_mro(typ):
  315. if cls in self.type_printers or self._in_deferred_types(cls):
  316. return self.type_printers[cls]
  317. # If we have reached here, the lookup failed.
  318. raise KeyError("No registered printer for {0!r}".format(typ))
  319. def for_type(self, typ, func=None):
  320. """Add a format function for a given type.
  321. Parameters
  322. -----------
  323. typ : type or '__module__.__name__' string for a type
  324. The class of the object that will be formatted using `func`.
  325. func : callable
  326. A callable for computing the format data.
  327. `func` will be called with the object to be formatted,
  328. and will return the raw data in this formatter's format.
  329. Subclasses may use a different call signature for the
  330. `func` argument.
  331. If `func` is None or not specified, there will be no change,
  332. only returning the current value.
  333. Returns
  334. -------
  335. oldfunc : callable
  336. The currently registered callable.
  337. If you are registering a new formatter,
  338. this will be the previous value (to enable restoring later).
  339. """
  340. # if string given, interpret as 'pkg.module.class_name'
  341. if isinstance(typ, string_types):
  342. type_module, type_name = typ.rsplit('.', 1)
  343. return self.for_type_by_name(type_module, type_name, func)
  344. try:
  345. oldfunc = self.lookup_by_type(typ)
  346. except KeyError:
  347. oldfunc = None
  348. if func is not None:
  349. self.type_printers[typ] = func
  350. return oldfunc
  351. def for_type_by_name(self, type_module, type_name, func=None):
  352. """Add a format function for a type specified by the full dotted
  353. module and name of the type, rather than the type of the object.
  354. Parameters
  355. ----------
  356. type_module : str
  357. The full dotted name of the module the type is defined in, like
  358. ``numpy``.
  359. type_name : str
  360. The name of the type (the class name), like ``dtype``
  361. func : callable
  362. A callable for computing the format data.
  363. `func` will be called with the object to be formatted,
  364. and will return the raw data in this formatter's format.
  365. Subclasses may use a different call signature for the
  366. `func` argument.
  367. If `func` is None or unspecified, there will be no change,
  368. only returning the current value.
  369. Returns
  370. -------
  371. oldfunc : callable
  372. The currently registered callable.
  373. If you are registering a new formatter,
  374. this will be the previous value (to enable restoring later).
  375. """
  376. key = (type_module, type_name)
  377. try:
  378. oldfunc = self.lookup_by_type("%s.%s" % key)
  379. except KeyError:
  380. oldfunc = None
  381. if func is not None:
  382. self.deferred_printers[key] = func
  383. return oldfunc
  384. def pop(self, typ, default=_raise_key_error):
  385. """Pop a formatter for the given type.
  386. Parameters
  387. ----------
  388. typ : type or '__module__.__name__' string for a type
  389. default : object
  390. value to be returned if no formatter is registered for typ.
  391. Returns
  392. -------
  393. obj : object
  394. The last registered object for the type.
  395. Raises
  396. ------
  397. KeyError if the type is not registered and default is not specified.
  398. """
  399. if isinstance(typ, string_types):
  400. typ_key = tuple(typ.rsplit('.',1))
  401. if typ_key not in self.deferred_printers:
  402. # We may have it cached in the type map. We will have to
  403. # iterate over all of the types to check.
  404. for cls in self.type_printers:
  405. if _mod_name_key(cls) == typ_key:
  406. old = self.type_printers.pop(cls)
  407. break
  408. else:
  409. old = default
  410. else:
  411. old = self.deferred_printers.pop(typ_key)
  412. else:
  413. if typ in self.type_printers:
  414. old = self.type_printers.pop(typ)
  415. else:
  416. old = self.deferred_printers.pop(_mod_name_key(typ), default)
  417. if old is _raise_key_error:
  418. raise KeyError("No registered value for {0!r}".format(typ))
  419. return old
  420. def _in_deferred_types(self, cls):
  421. """
  422. Check if the given class is specified in the deferred type registry.
  423. Successful matches will be moved to the regular type registry for future use.
  424. """
  425. mod = getattr(cls, '__module__', None)
  426. name = getattr(cls, '__name__', None)
  427. key = (mod, name)
  428. if key in self.deferred_printers:
  429. # Move the printer over to the regular registry.
  430. printer = self.deferred_printers.pop(key)
  431. self.type_printers[cls] = printer
  432. return True
  433. return False
  434. class PlainTextFormatter(BaseFormatter):
  435. """The default pretty-printer.
  436. This uses :mod:`IPython.lib.pretty` to compute the format data of
  437. the object. If the object cannot be pretty printed, :func:`repr` is used.
  438. See the documentation of :mod:`IPython.lib.pretty` for details on
  439. how to write pretty printers. Here is a simple example::
  440. def dtype_pprinter(obj, p, cycle):
  441. if cycle:
  442. return p.text('dtype(...)')
  443. if hasattr(obj, 'fields'):
  444. if obj.fields is None:
  445. p.text(repr(obj))
  446. else:
  447. p.begin_group(7, 'dtype([')
  448. for i, field in enumerate(obj.descr):
  449. if i > 0:
  450. p.text(',')
  451. p.breakable()
  452. p.pretty(field)
  453. p.end_group(7, '])')
  454. """
  455. # The format type of data returned.
  456. format_type = Unicode('text/plain')
  457. # This subclass ignores this attribute as it always need to return
  458. # something.
  459. enabled = Bool(True).tag(config=False)
  460. max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
  461. help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
  462. Set to 0 to disable truncation.
  463. """
  464. ).tag(config=True)
  465. # Look for a _repr_pretty_ methods to use for pretty printing.
  466. print_method = ObjectName('_repr_pretty_')
  467. # Whether to pretty-print or not.
  468. pprint = Bool(True).tag(config=True)
  469. # Whether to be verbose or not.
  470. verbose = Bool(False).tag(config=True)
  471. # The maximum width.
  472. max_width = Integer(79).tag(config=True)
  473. # The newline character.
  474. newline = Unicode('\n').tag(config=True)
  475. # format-string for pprinting floats
  476. float_format = Unicode('%r')
  477. # setter for float precision, either int or direct format-string
  478. float_precision = CUnicode('').tag(config=True)
  479. @observe('float_precision')
  480. def _float_precision_changed(self, change):
  481. """float_precision changed, set float_format accordingly.
  482. float_precision can be set by int or str.
  483. This will set float_format, after interpreting input.
  484. If numpy has been imported, numpy print precision will also be set.
  485. integer `n` sets format to '%.nf', otherwise, format set directly.
  486. An empty string returns to defaults (repr for float, 8 for numpy).
  487. This parameter can be set via the '%precision' magic.
  488. """
  489. new = change['new']
  490. if '%' in new:
  491. # got explicit format string
  492. fmt = new
  493. try:
  494. fmt%3.14159
  495. except Exception:
  496. raise ValueError("Precision must be int or format string, not %r"%new)
  497. elif new:
  498. # otherwise, should be an int
  499. try:
  500. i = int(new)
  501. assert i >= 0
  502. except ValueError:
  503. raise ValueError("Precision must be int or format string, not %r"%new)
  504. except AssertionError:
  505. raise ValueError("int precision must be non-negative, not %r"%i)
  506. fmt = '%%.%if'%i
  507. if 'numpy' in sys.modules:
  508. # set numpy precision if it has been imported
  509. import numpy
  510. numpy.set_printoptions(precision=i)
  511. else:
  512. # default back to repr
  513. fmt = '%r'
  514. if 'numpy' in sys.modules:
  515. import numpy
  516. # numpy default is 8
  517. numpy.set_printoptions(precision=8)
  518. self.float_format = fmt
  519. # Use the default pretty printers from IPython.lib.pretty.
  520. @default('singleton_printers')
  521. def _singleton_printers_default(self):
  522. return pretty._singleton_pprinters.copy()
  523. @default('type_printers')
  524. def _type_printers_default(self):
  525. d = pretty._type_pprinters.copy()
  526. d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
  527. return d
  528. @default('deferred_printers')
  529. def _deferred_printers_default(self):
  530. return pretty._deferred_type_pprinters.copy()
  531. #### FormatterABC interface ####
  532. @catch_format_error
  533. def __call__(self, obj):
  534. """Compute the pretty representation of the object."""
  535. if not self.pprint:
  536. return repr(obj)
  537. else:
  538. # handle str and unicode on Python 2
  539. # io.StringIO only accepts unicode,
  540. # cStringIO doesn't handle unicode on py2,
  541. # StringIO allows str, unicode but only ascii str
  542. stream = pretty.CUnicodeIO()
  543. printer = pretty.RepresentationPrinter(stream, self.verbose,
  544. self.max_width, self.newline,
  545. max_seq_length=self.max_seq_length,
  546. singleton_pprinters=self.singleton_printers,
  547. type_pprinters=self.type_printers,
  548. deferred_pprinters=self.deferred_printers)
  549. printer.pretty(obj)
  550. printer.flush()
  551. return stream.getvalue()
  552. class HTMLFormatter(BaseFormatter):
  553. """An HTML formatter.
  554. To define the callables that compute the HTML representation of your
  555. objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
  556. or :meth:`for_type_by_name` methods to register functions that handle
  557. this.
  558. The return value of this formatter should be a valid HTML snippet that
  559. could be injected into an existing DOM. It should *not* include the
  560. ```<html>`` or ```<body>`` tags.
  561. """
  562. format_type = Unicode('text/html')
  563. print_method = ObjectName('_repr_html_')
  564. class MarkdownFormatter(BaseFormatter):
  565. """A Markdown formatter.
  566. To define the callables that compute the Markdown representation of your
  567. objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
  568. or :meth:`for_type_by_name` methods to register functions that handle
  569. this.
  570. The return value of this formatter should be a valid Markdown.
  571. """
  572. format_type = Unicode('text/markdown')
  573. print_method = ObjectName('_repr_markdown_')
  574. class SVGFormatter(BaseFormatter):
  575. """An SVG formatter.
  576. To define the callables that compute the SVG representation of your
  577. objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
  578. or :meth:`for_type_by_name` methods to register functions that handle
  579. this.
  580. The return value of this formatter should be valid SVG enclosed in
  581. ```<svg>``` tags, that could be injected into an existing DOM. It should
  582. *not* include the ```<html>`` or ```<body>`` tags.
  583. """
  584. format_type = Unicode('image/svg+xml')
  585. print_method = ObjectName('_repr_svg_')
  586. class PNGFormatter(BaseFormatter):
  587. """A PNG formatter.
  588. To define the callables that compute the PNG representation of your
  589. objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
  590. or :meth:`for_type_by_name` methods to register functions that handle
  591. this.
  592. The return value of this formatter should be raw PNG data, *not*
  593. base64 encoded.
  594. """
  595. format_type = Unicode('image/png')
  596. print_method = ObjectName('_repr_png_')
  597. _return_type = (bytes, unicode_type)
  598. class JPEGFormatter(BaseFormatter):
  599. """A JPEG formatter.
  600. To define the callables that compute the JPEG representation of your
  601. objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
  602. or :meth:`for_type_by_name` methods to register functions that handle
  603. this.
  604. The return value of this formatter should be raw JPEG data, *not*
  605. base64 encoded.
  606. """
  607. format_type = Unicode('image/jpeg')
  608. print_method = ObjectName('_repr_jpeg_')
  609. _return_type = (bytes, unicode_type)
  610. class LatexFormatter(BaseFormatter):
  611. """A LaTeX formatter.
  612. To define the callables that compute the LaTeX representation of your
  613. objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
  614. or :meth:`for_type_by_name` methods to register functions that handle
  615. this.
  616. The return value of this formatter should be a valid LaTeX equation,
  617. enclosed in either ```$```, ```$$``` or another LaTeX equation
  618. environment.
  619. """
  620. format_type = Unicode('text/latex')
  621. print_method = ObjectName('_repr_latex_')
  622. class JSONFormatter(BaseFormatter):
  623. """A JSON string formatter.
  624. To define the callables that compute the JSONable representation of
  625. your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
  626. or :meth:`for_type_by_name` methods to register functions that handle
  627. this.
  628. The return value of this formatter should be a JSONable list or dict.
  629. JSON scalars (None, number, string) are not allowed, only dict or list containers.
  630. """
  631. format_type = Unicode('application/json')
  632. _return_type = (list, dict)
  633. print_method = ObjectName('_repr_json_')
  634. def _check_return(self, r, obj):
  635. """Check that a return value is appropriate
  636. Return the value if so, None otherwise, warning if invalid.
  637. """
  638. if r is None:
  639. return
  640. md = None
  641. if isinstance(r, tuple):
  642. # unpack data, metadata tuple for type checking on first element
  643. r, md = r
  644. # handle deprecated JSON-as-string form from IPython < 3
  645. if isinstance(r, string_types):
  646. warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
  647. FormatterWarning)
  648. r = json.loads(r)
  649. if md is not None:
  650. # put the tuple back together
  651. r = (r, md)
  652. return super(JSONFormatter, self)._check_return(r, obj)
  653. class JavascriptFormatter(BaseFormatter):
  654. """A Javascript formatter.
  655. To define the callables that compute the Javascript representation of
  656. your objects, define a :meth:`_repr_javascript_` method or use the
  657. :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
  658. that handle this.
  659. The return value of this formatter should be valid Javascript code and
  660. should *not* be enclosed in ```<script>``` tags.
  661. """
  662. format_type = Unicode('application/javascript')
  663. print_method = ObjectName('_repr_javascript_')
  664. class PDFFormatter(BaseFormatter):
  665. """A PDF formatter.
  666. To define the callables that compute the PDF representation of your
  667. objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
  668. or :meth:`for_type_by_name` methods to register functions that handle
  669. this.
  670. The return value of this formatter should be raw PDF data, *not*
  671. base64 encoded.
  672. """
  673. format_type = Unicode('application/pdf')
  674. print_method = ObjectName('_repr_pdf_')
  675. _return_type = (bytes, unicode_type)
  676. class IPythonDisplayFormatter(BaseFormatter):
  677. """A Formatter for objects that know how to display themselves.
  678. To define the callables that compute the representation of your
  679. objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
  680. or :meth:`for_type_by_name` methods to register functions that handle
  681. this. Unlike mime-type displays, this method should not return anything,
  682. instead calling any appropriate display methods itself.
  683. This display formatter has highest priority.
  684. If it fires, no other display formatter will be called.
  685. """
  686. print_method = ObjectName('_ipython_display_')
  687. _return_type = (type(None), bool)
  688. @catch_format_error
  689. def __call__(self, obj):
  690. """Compute the format for an object."""
  691. if self.enabled:
  692. # lookup registered printer
  693. try:
  694. printer = self.lookup(obj)
  695. except KeyError:
  696. pass
  697. else:
  698. printer(obj)
  699. return True
  700. # Finally look for special method names
  701. method = get_real_method(obj, self.print_method)
  702. if method is not None:
  703. method()
  704. return True
  705. FormatterABC.register(BaseFormatter)
  706. FormatterABC.register(PlainTextFormatter)
  707. FormatterABC.register(HTMLFormatter)
  708. FormatterABC.register(MarkdownFormatter)
  709. FormatterABC.register(SVGFormatter)
  710. FormatterABC.register(PNGFormatter)
  711. FormatterABC.register(PDFFormatter)
  712. FormatterABC.register(JPEGFormatter)
  713. FormatterABC.register(LatexFormatter)
  714. FormatterABC.register(JSONFormatter)
  715. FormatterABC.register(JavascriptFormatter)
  716. FormatterABC.register(IPythonDisplayFormatter)
  717. def format_display_data(obj, include=None, exclude=None):
  718. """Return a format data dict for an object.
  719. By default all format types will be computed.
  720. The following MIME types are currently implemented:
  721. * text/plain
  722. * text/html
  723. * text/markdown
  724. * text/latex
  725. * application/json
  726. * application/javascript
  727. * application/pdf
  728. * image/png
  729. * image/jpeg
  730. * image/svg+xml
  731. Parameters
  732. ----------
  733. obj : object
  734. The Python object whose format data will be computed.
  735. Returns
  736. -------
  737. format_dict : dict
  738. A dictionary of key/value pairs, one or each format that was
  739. generated for the object. The keys are the format types, which
  740. will usually be MIME type strings and the values and JSON'able
  741. data structure containing the raw data for the representation in
  742. that format.
  743. include : list or tuple, optional
  744. A list of format type strings (MIME types) to include in the
  745. format data dict. If this is set *only* the format types included
  746. in this list will be computed.
  747. exclude : list or tuple, optional
  748. A list of format type string (MIME types) to exclue in the format
  749. data dict. If this is set all format types will be computed,
  750. except for those included in this argument.
  751. """
  752. from IPython.core.interactiveshell import InteractiveShell
  753. return InteractiveShell.instance().display_formatter.format(
  754. obj,
  755. include,
  756. exclude
  757. )