##// END OF EJS Templates
update name, docstring for warn_format_error...
Min RK -
Show More
@@ -1,970 +1,970 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4 Inheritance diagram:
5 5
6 6 .. inheritance-diagram:: IPython.core.formatters
7 7 :parts: 3
8 8 """
9 9
10 10 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12
13 13 import abc
14 14 import inspect
15 15 import json
16 16 import sys
17 17 import traceback
18 18 import warnings
19 19
20 20 from IPython.external.decorator import decorator
21 21
22 22 from IPython.config.configurable import Configurable
23 23 from IPython.core.getipython import get_ipython
24 24 from IPython.lib import pretty
25 25 from IPython.utils.traitlets import (
26 26 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
27 27 ForwardDeclaredInstance,
28 28 )
29 29 from IPython.utils.py3compat import (
30 30 unicode_to_str, with_metaclass, PY3, string_types, unicode_type,
31 31 )
32 32
33 33 if PY3:
34 34 from io import StringIO
35 35 else:
36 36 from StringIO import StringIO
37 37
38 38
39 39 #-----------------------------------------------------------------------------
40 40 # The main DisplayFormatter class
41 41 #-----------------------------------------------------------------------------
42 42
43 43
44 44 def _safe_get_formatter_method(obj, name):
45 45 """Safely get a formatter method
46 46
47 47 - Classes cannot have formatter methods, only instance
48 48 - protect against proxy objects that claim to have everything
49 49 """
50 50 if inspect.isclass(obj):
51 51 # repr methods only make sense on instances, not classes
52 52 return None
53 53 method = pretty._safe_getattr(obj, name, None)
54 54 if callable(method):
55 55 # obj claims to have repr method...
56 56 if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)):
57 57 # ...but don't trust proxy objects that claim to have everything
58 58 return None
59 59 return method
60 60
61 61
62 62 class DisplayFormatter(Configurable):
63 63
64 64 # When set to true only the default plain text formatter will be used.
65 65 plain_text_only = Bool(False, config=True)
66 66 def _plain_text_only_changed(self, name, old, new):
67 67 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
68 68
69 69 Use DisplayFormatter.active_types = ['text/plain']
70 70 for the same effect.
71 71 """, DeprecationWarning)
72 72 if new:
73 73 self.active_types = ['text/plain']
74 74 else:
75 75 self.active_types = self.format_types
76 76
77 77 active_types = List(Unicode, config=True,
78 78 help="""List of currently active mime-types to display.
79 79 You can use this to set a white-list for formats to display.
80 80
81 81 Most users will not need to change this value.
82 82 """)
83 83 def _active_types_default(self):
84 84 return self.format_types
85 85
86 86 def _active_types_changed(self, name, old, new):
87 87 for key, formatter in self.formatters.items():
88 88 if key in new:
89 89 formatter.enabled = True
90 90 else:
91 91 formatter.enabled = False
92 92
93 93 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
94 94 def _ipython_display_formatter_default(self):
95 95 return IPythonDisplayFormatter(parent=self)
96 96
97 97 # A dict of formatter whose keys are format types (MIME types) and whose
98 98 # values are subclasses of BaseFormatter.
99 99 formatters = Dict()
100 100 def _formatters_default(self):
101 101 """Activate the default formatters."""
102 102 formatter_classes = [
103 103 PlainTextFormatter,
104 104 HTMLFormatter,
105 105 MarkdownFormatter,
106 106 SVGFormatter,
107 107 PNGFormatter,
108 108 PDFFormatter,
109 109 JPEGFormatter,
110 110 LatexFormatter,
111 111 JSONFormatter,
112 112 JavascriptFormatter
113 113 ]
114 114 d = {}
115 115 for cls in formatter_classes:
116 116 f = cls(parent=self)
117 117 d[f.format_type] = f
118 118 return d
119 119
120 120 def format(self, obj, include=None, exclude=None):
121 121 """Return a format data dict for an object.
122 122
123 123 By default all format types will be computed.
124 124
125 125 The following MIME types are currently implemented:
126 126
127 127 * text/plain
128 128 * text/html
129 129 * text/markdown
130 130 * text/latex
131 131 * application/json
132 132 * application/javascript
133 133 * application/pdf
134 134 * image/png
135 135 * image/jpeg
136 136 * image/svg+xml
137 137
138 138 Parameters
139 139 ----------
140 140 obj : object
141 141 The Python object whose format data will be computed.
142 142 include : list or tuple, optional
143 143 A list of format type strings (MIME types) to include in the
144 144 format data dict. If this is set *only* the format types included
145 145 in this list will be computed.
146 146 exclude : list or tuple, optional
147 147 A list of format type string (MIME types) to exclude in the format
148 148 data dict. If this is set all format types will be computed,
149 149 except for those included in this argument.
150 150
151 151 Returns
152 152 -------
153 153 (format_dict, metadata_dict) : tuple of two dicts
154 154
155 155 format_dict is a dictionary of key/value pairs, one of each format that was
156 156 generated for the object. The keys are the format types, which
157 157 will usually be MIME type strings and the values and JSON'able
158 158 data structure containing the raw data for the representation in
159 159 that format.
160 160
161 161 metadata_dict is a dictionary of metadata about each mime-type output.
162 162 Its keys will be a strict subset of the keys in format_dict.
163 163 """
164 164 format_dict = {}
165 165 md_dict = {}
166 166
167 167 if self.ipython_display_formatter(obj):
168 168 # object handled itself, don't proceed
169 169 return {}, {}
170 170
171 171 for format_type, formatter in self.formatters.items():
172 172 if include and format_type not in include:
173 173 continue
174 174 if exclude and format_type in exclude:
175 175 continue
176 176
177 177 md = None
178 178 try:
179 179 data = formatter(obj)
180 180 except:
181 181 # FIXME: log the exception
182 182 raise
183 183
184 184 # formatters can return raw data or (data, metadata)
185 185 if isinstance(data, tuple) and len(data) == 2:
186 186 data, md = data
187 187
188 188 if data is not None:
189 189 format_dict[format_type] = data
190 190 if md is not None:
191 191 md_dict[format_type] = md
192 192
193 193 return format_dict, md_dict
194 194
195 195 @property
196 196 def format_types(self):
197 197 """Return the format types (MIME types) of the active formatters."""
198 198 return list(self.formatters.keys())
199 199
200 200
201 201 #-----------------------------------------------------------------------------
202 202 # Formatters for specific format types (text, html, svg, etc.)
203 203 #-----------------------------------------------------------------------------
204 204
205 205
206 206 def _safe_repr(obj):
207 207 """Try to return a repr of an object
208 208
209 209 always returns a string, at least.
210 210 """
211 211 try:
212 212 return repr(obj)
213 213 except Exception as e:
214 214 return "un-repr-able object (%r)" % e
215 215
216 216
217 217 class FormatterWarning(UserWarning):
218 218 """Warning class for errors in formatters"""
219 219
220 220 @decorator
221 def warn_format_error(method, self, *args, **kwargs):
222 """decorator for warning on failed format call"""
221 def catch_format_error(method, self, *args, **kwargs):
222 """show traceback on failed format call"""
223 223 try:
224 224 r = method(self, *args, **kwargs)
225 225 except NotImplementedError:
226 226 # don't warn on NotImplementedErrors
227 227 return None
228 228 except Exception:
229 229 exc_info = sys.exc_info()
230 230 ip = get_ipython()
231 231 if ip is not None:
232 232 ip.showtraceback(exc_info)
233 233 else:
234 234 traceback.print_exception(*exc_info)
235 235 return None
236 236 return self._check_return(r, args[0])
237 237
238 238
239 239 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
240 240 """ Abstract base class for Formatters.
241 241
242 242 A formatter is a callable class that is responsible for computing the
243 243 raw format data for a particular format type (MIME type). For example,
244 244 an HTML formatter would have a format type of `text/html` and would return
245 245 the HTML representation of the object when called.
246 246 """
247 247
248 248 # The format type of the data returned, usually a MIME type.
249 249 format_type = 'text/plain'
250 250
251 251 # Is the formatter enabled...
252 252 enabled = True
253 253
254 254 @abc.abstractmethod
255 255 def __call__(self, obj):
256 256 """Return a JSON'able representation of the object.
257 257
258 258 If the object cannot be formatted by this formatter,
259 259 warn and return None.
260 260 """
261 261 return repr(obj)
262 262
263 263
264 264 def _mod_name_key(typ):
265 265 """Return a (__module__, __name__) tuple for a type.
266 266
267 267 Used as key in Formatter.deferred_printers.
268 268 """
269 269 module = getattr(typ, '__module__', None)
270 270 name = getattr(typ, '__name__', None)
271 271 return (module, name)
272 272
273 273
274 274 def _get_type(obj):
275 275 """Return the type of an instance (old and new-style)"""
276 276 return getattr(obj, '__class__', None) or type(obj)
277 277
278 278 _raise_key_error = object()
279 279
280 280
281 281 class BaseFormatter(Configurable):
282 282 """A base formatter class that is configurable.
283 283
284 284 This formatter should usually be used as the base class of all formatters.
285 285 It is a traited :class:`Configurable` class and includes an extensible
286 286 API for users to determine how their objects are formatted. The following
287 287 logic is used to find a function to format an given object.
288 288
289 289 1. The object is introspected to see if it has a method with the name
290 290 :attr:`print_method`. If is does, that object is passed to that method
291 291 for formatting.
292 292 2. If no print method is found, three internal dictionaries are consulted
293 293 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
294 294 and :attr:`deferred_printers`.
295 295
296 296 Users should use these dictionaries to register functions that will be
297 297 used to compute the format data for their objects (if those objects don't
298 298 have the special print methods). The easiest way of using these
299 299 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
300 300 methods.
301 301
302 302 If no function/callable is found to compute the format data, ``None`` is
303 303 returned and this format type is not used.
304 304 """
305 305
306 306 format_type = Unicode('text/plain')
307 307 _return_type = string_types
308 308
309 309 enabled = Bool(True, config=True)
310 310
311 311 print_method = ObjectName('__repr__')
312 312
313 313 # The singleton printers.
314 314 # Maps the IDs of the builtin singleton objects to the format functions.
315 315 singleton_printers = Dict(config=True)
316 316
317 317 # The type-specific printers.
318 318 # Map type objects to the format functions.
319 319 type_printers = Dict(config=True)
320 320
321 321 # The deferred-import type-specific printers.
322 322 # Map (modulename, classname) pairs to the format functions.
323 323 deferred_printers = Dict(config=True)
324 324
325 @warn_format_error
325 @catch_format_error
326 326 def __call__(self, obj):
327 327 """Compute the format for an object."""
328 328 if self.enabled:
329 329 # lookup registered printer
330 330 try:
331 331 printer = self.lookup(obj)
332 332 except KeyError:
333 333 pass
334 334 else:
335 335 return printer(obj)
336 336 # Finally look for special method names
337 337 method = _safe_get_formatter_method(obj, self.print_method)
338 338 if method is not None:
339 339 return method()
340 340 return None
341 341 else:
342 342 return None
343 343
344 344 def __contains__(self, typ):
345 345 """map in to lookup_by_type"""
346 346 try:
347 347 self.lookup_by_type(typ)
348 348 except KeyError:
349 349 return False
350 350 else:
351 351 return True
352 352
353 353 def _check_return(self, r, obj):
354 354 """Check that a return value is appropriate
355 355
356 356 Return the value if so, None otherwise, warning if invalid.
357 357 """
358 358 if r is None or isinstance(r, self._return_type) or \
359 359 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
360 360 return r
361 361 else:
362 362 warnings.warn(
363 363 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
364 364 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
365 365 FormatterWarning
366 366 )
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 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True,
593 593 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
594 594
595 595 Set to 0 to disable truncation.
596 596 """
597 597 )
598 598
599 599 # Look for a _repr_pretty_ methods to use for pretty printing.
600 600 print_method = ObjectName('_repr_pretty_')
601 601
602 602 # Whether to pretty-print or not.
603 603 pprint = Bool(True, config=True)
604 604
605 605 # Whether to be verbose or not.
606 606 verbose = Bool(False, config=True)
607 607
608 608 # The maximum width.
609 609 max_width = Integer(79, config=True)
610 610
611 611 # The newline character.
612 612 newline = Unicode('\n', config=True)
613 613
614 614 # format-string for pprinting floats
615 615 float_format = Unicode('%r')
616 616 # setter for float precision, either int or direct format-string
617 617 float_precision = CUnicode('', config=True)
618 618
619 619 def _float_precision_changed(self, name, old, new):
620 620 """float_precision changed, set float_format accordingly.
621 621
622 622 float_precision can be set by int or str.
623 623 This will set float_format, after interpreting input.
624 624 If numpy has been imported, numpy print precision will also be set.
625 625
626 626 integer `n` sets format to '%.nf', otherwise, format set directly.
627 627
628 628 An empty string returns to defaults (repr for float, 8 for numpy).
629 629
630 630 This parameter can be set via the '%precision' magic.
631 631 """
632 632
633 633 if '%' in new:
634 634 # got explicit format string
635 635 fmt = new
636 636 try:
637 637 fmt%3.14159
638 638 except Exception:
639 639 raise ValueError("Precision must be int or format string, not %r"%new)
640 640 elif new:
641 641 # otherwise, should be an int
642 642 try:
643 643 i = int(new)
644 644 assert i >= 0
645 645 except ValueError:
646 646 raise ValueError("Precision must be int or format string, not %r"%new)
647 647 except AssertionError:
648 648 raise ValueError("int precision must be non-negative, not %r"%i)
649 649
650 650 fmt = '%%.%if'%i
651 651 if 'numpy' in sys.modules:
652 652 # set numpy precision if it has been imported
653 653 import numpy
654 654 numpy.set_printoptions(precision=i)
655 655 else:
656 656 # default back to repr
657 657 fmt = '%r'
658 658 if 'numpy' in sys.modules:
659 659 import numpy
660 660 # numpy default is 8
661 661 numpy.set_printoptions(precision=8)
662 662 self.float_format = fmt
663 663
664 664 # Use the default pretty printers from IPython.lib.pretty.
665 665 def _singleton_printers_default(self):
666 666 return pretty._singleton_pprinters.copy()
667 667
668 668 def _type_printers_default(self):
669 669 d = pretty._type_pprinters.copy()
670 670 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
671 671 return d
672 672
673 673 def _deferred_printers_default(self):
674 674 return pretty._deferred_type_pprinters.copy()
675 675
676 676 #### FormatterABC interface ####
677 677
678 @warn_format_error
678 @catch_format_error
679 679 def __call__(self, obj):
680 680 """Compute the pretty representation of the object."""
681 681 if not self.pprint:
682 682 return repr(obj)
683 683 else:
684 684 # This uses use StringIO, as cStringIO doesn't handle unicode.
685 685 stream = StringIO()
686 686 # self.newline.encode() is a quick fix for issue gh-597. We need to
687 687 # ensure that stream does not get a mix of unicode and bytestrings,
688 688 # or it will cause trouble.
689 689 printer = pretty.RepresentationPrinter(stream, self.verbose,
690 690 self.max_width, unicode_to_str(self.newline),
691 691 max_seq_length=self.max_seq_length,
692 692 singleton_pprinters=self.singleton_printers,
693 693 type_pprinters=self.type_printers,
694 694 deferred_pprinters=self.deferred_printers)
695 695 printer.pretty(obj)
696 696 printer.flush()
697 697 return stream.getvalue()
698 698
699 699
700 700 class HTMLFormatter(BaseFormatter):
701 701 """An HTML formatter.
702 702
703 703 To define the callables that compute the HTML representation of your
704 704 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
705 705 or :meth:`for_type_by_name` methods to register functions that handle
706 706 this.
707 707
708 708 The return value of this formatter should be a valid HTML snippet that
709 709 could be injected into an existing DOM. It should *not* include the
710 710 ```<html>`` or ```<body>`` tags.
711 711 """
712 712 format_type = Unicode('text/html')
713 713
714 714 print_method = ObjectName('_repr_html_')
715 715
716 716
717 717 class MarkdownFormatter(BaseFormatter):
718 718 """A Markdown formatter.
719 719
720 720 To define the callables that compute the Markdown representation of your
721 721 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
722 722 or :meth:`for_type_by_name` methods to register functions that handle
723 723 this.
724 724
725 725 The return value of this formatter should be a valid Markdown.
726 726 """
727 727 format_type = Unicode('text/markdown')
728 728
729 729 print_method = ObjectName('_repr_markdown_')
730 730
731 731 class SVGFormatter(BaseFormatter):
732 732 """An SVG formatter.
733 733
734 734 To define the callables that compute the SVG representation of your
735 735 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
736 736 or :meth:`for_type_by_name` methods to register functions that handle
737 737 this.
738 738
739 739 The return value of this formatter should be valid SVG enclosed in
740 740 ```<svg>``` tags, that could be injected into an existing DOM. It should
741 741 *not* include the ```<html>`` or ```<body>`` tags.
742 742 """
743 743 format_type = Unicode('image/svg+xml')
744 744
745 745 print_method = ObjectName('_repr_svg_')
746 746
747 747
748 748 class PNGFormatter(BaseFormatter):
749 749 """A PNG formatter.
750 750
751 751 To define the callables that compute the PNG representation of your
752 752 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
753 753 or :meth:`for_type_by_name` methods to register functions that handle
754 754 this.
755 755
756 756 The return value of this formatter should be raw PNG data, *not*
757 757 base64 encoded.
758 758 """
759 759 format_type = Unicode('image/png')
760 760
761 761 print_method = ObjectName('_repr_png_')
762 762
763 763 _return_type = (bytes, unicode_type)
764 764
765 765
766 766 class JPEGFormatter(BaseFormatter):
767 767 """A JPEG formatter.
768 768
769 769 To define the callables that compute the JPEG representation of your
770 770 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
771 771 or :meth:`for_type_by_name` methods to register functions that handle
772 772 this.
773 773
774 774 The return value of this formatter should be raw JPEG data, *not*
775 775 base64 encoded.
776 776 """
777 777 format_type = Unicode('image/jpeg')
778 778
779 779 print_method = ObjectName('_repr_jpeg_')
780 780
781 781 _return_type = (bytes, unicode_type)
782 782
783 783
784 784 class LatexFormatter(BaseFormatter):
785 785 """A LaTeX formatter.
786 786
787 787 To define the callables that compute the LaTeX representation of your
788 788 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
789 789 or :meth:`for_type_by_name` methods to register functions that handle
790 790 this.
791 791
792 792 The return value of this formatter should be a valid LaTeX equation,
793 793 enclosed in either ```$```, ```$$``` or another LaTeX equation
794 794 environment.
795 795 """
796 796 format_type = Unicode('text/latex')
797 797
798 798 print_method = ObjectName('_repr_latex_')
799 799
800 800
801 801 class JSONFormatter(BaseFormatter):
802 802 """A JSON string formatter.
803 803
804 804 To define the callables that compute the JSONable representation of
805 805 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
806 806 or :meth:`for_type_by_name` methods to register functions that handle
807 807 this.
808 808
809 809 The return value of this formatter should be a JSONable list or dict.
810 810 JSON scalars (None, number, string) are not allowed, only dict or list containers.
811 811 """
812 812 format_type = Unicode('application/json')
813 813 _return_type = (list, dict)
814 814
815 815 print_method = ObjectName('_repr_json_')
816 816
817 817 def _check_return(self, r, obj):
818 818 """Check that a return value is appropriate
819 819
820 820 Return the value if so, None otherwise, warning if invalid.
821 821 """
822 822 if r is None:
823 823 return
824 824 md = None
825 825 if isinstance(r, tuple):
826 826 # unpack data, metadata tuple for type checking on first element
827 827 r, md = r
828 828
829 829 # handle deprecated JSON-as-string form from IPython < 3
830 830 if isinstance(r, string_types):
831 831 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
832 832 FormatterWarning)
833 833 r = json.loads(r)
834 834
835 835 if md is not None:
836 836 # put the tuple back together
837 837 r = (r, md)
838 838 return super(JSONFormatter, self)._check_return(r, obj)
839 839
840 840
841 841 class JavascriptFormatter(BaseFormatter):
842 842 """A Javascript formatter.
843 843
844 844 To define the callables that compute the Javascript representation of
845 845 your objects, define a :meth:`_repr_javascript_` method or use the
846 846 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
847 847 that handle this.
848 848
849 849 The return value of this formatter should be valid Javascript code and
850 850 should *not* be enclosed in ```<script>``` tags.
851 851 """
852 852 format_type = Unicode('application/javascript')
853 853
854 854 print_method = ObjectName('_repr_javascript_')
855 855
856 856
857 857 class PDFFormatter(BaseFormatter):
858 858 """A PDF formatter.
859 859
860 860 To define the callables that compute the PDF representation of your
861 861 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
862 862 or :meth:`for_type_by_name` methods to register functions that handle
863 863 this.
864 864
865 865 The return value of this formatter should be raw PDF data, *not*
866 866 base64 encoded.
867 867 """
868 868 format_type = Unicode('application/pdf')
869 869
870 870 print_method = ObjectName('_repr_pdf_')
871 871
872 872 _return_type = (bytes, unicode_type)
873 873
874 874 class IPythonDisplayFormatter(BaseFormatter):
875 875 """A Formatter for objects that know how to display themselves.
876 876
877 877 To define the callables that compute the representation of your
878 878 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
879 879 or :meth:`for_type_by_name` methods to register functions that handle
880 880 this. Unlike mime-type displays, this method should not return anything,
881 881 instead calling any appropriate display methods itself.
882 882
883 883 This display formatter has highest priority.
884 884 If it fires, no other display formatter will be called.
885 885 """
886 886 print_method = ObjectName('_ipython_display_')
887 887 _return_type = (type(None), bool)
888 888
889 889
890 @warn_format_error
890 @catch_format_error
891 891 def __call__(self, obj):
892 892 """Compute the format for an object."""
893 893 if self.enabled:
894 894 # lookup registered printer
895 895 try:
896 896 printer = self.lookup(obj)
897 897 except KeyError:
898 898 pass
899 899 else:
900 900 printer(obj)
901 901 return True
902 902 # Finally look for special method names
903 903 method = _safe_get_formatter_method(obj, self.print_method)
904 904 if method is not None:
905 905 method()
906 906 return True
907 907
908 908
909 909 FormatterABC.register(BaseFormatter)
910 910 FormatterABC.register(PlainTextFormatter)
911 911 FormatterABC.register(HTMLFormatter)
912 912 FormatterABC.register(MarkdownFormatter)
913 913 FormatterABC.register(SVGFormatter)
914 914 FormatterABC.register(PNGFormatter)
915 915 FormatterABC.register(PDFFormatter)
916 916 FormatterABC.register(JPEGFormatter)
917 917 FormatterABC.register(LatexFormatter)
918 918 FormatterABC.register(JSONFormatter)
919 919 FormatterABC.register(JavascriptFormatter)
920 920 FormatterABC.register(IPythonDisplayFormatter)
921 921
922 922
923 923 def format_display_data(obj, include=None, exclude=None):
924 924 """Return a format data dict for an object.
925 925
926 926 By default all format types will be computed.
927 927
928 928 The following MIME types are currently implemented:
929 929
930 930 * text/plain
931 931 * text/html
932 932 * text/markdown
933 933 * text/latex
934 934 * application/json
935 935 * application/javascript
936 936 * application/pdf
937 937 * image/png
938 938 * image/jpeg
939 939 * image/svg+xml
940 940
941 941 Parameters
942 942 ----------
943 943 obj : object
944 944 The Python object whose format data will be computed.
945 945
946 946 Returns
947 947 -------
948 948 format_dict : dict
949 949 A dictionary of key/value pairs, one or each format that was
950 950 generated for the object. The keys are the format types, which
951 951 will usually be MIME type strings and the values and JSON'able
952 952 data structure containing the raw data for the representation in
953 953 that format.
954 954 include : list or tuple, optional
955 955 A list of format type strings (MIME types) to include in the
956 956 format data dict. If this is set *only* the format types included
957 957 in this list will be computed.
958 958 exclude : list or tuple, optional
959 959 A list of format type string (MIME types) to exclue in the format
960 960 data dict. If this is set all format types will be computed,
961 961 except for those included in this argument.
962 962 """
963 963 from IPython.core.interactiveshell import InteractiveShell
964 964
965 965 InteractiveShell.instance().display_formatter.format(
966 966 obj,
967 967 include,
968 968 exclude
969 969 )
970 970
General Comments 0
You need to be logged in to leave comments. Login now