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