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