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