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