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