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