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