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