##// END OF EJS Templates
Merge pull request #10557 from ipython/auto-backport-of-pr-10543...
Matthias Bussonnier -
r23651:e0d9c069 merge
parent child Browse files
Show More
@@ -1,1008 +1,1037 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 json
15 15 import sys
16 16 import traceback
17 17 import warnings
18 18
19 19 from decorator import decorator
20 20
21 21 from traitlets.config.configurable import Configurable
22 22 from IPython.core.getipython import get_ipython
23 23 from IPython.utils.sentinel import Sentinel
24 24 from IPython.utils.dir2 import get_real_method
25 25 from IPython.lib import pretty
26 26 from traitlets import (
27 27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 28 ForwardDeclaredInstance,
29 29 default, observe,
30 30 )
31 31 from IPython.utils.py3compat import (
32 32 with_metaclass, string_types, unicode_type,
33 33 )
34 34
35 35
36 36 class DisplayFormatter(Configurable):
37 37
38 38 active_types = List(Unicode(),
39 39 help="""List of currently active mime-types to display.
40 40 You can use this to set a white-list for formats to display.
41 41
42 42 Most users will not need to change this value.
43 43 """).tag(config=True)
44 44
45 45 @default('active_types')
46 46 def _active_types_default(self):
47 47 return self.format_types
48 48
49 49 @observe('active_types')
50 50 def _active_types_changed(self, change):
51 51 for key, formatter in self.formatters.items():
52 52 if key in change['new']:
53 53 formatter.enabled = True
54 54 else:
55 55 formatter.enabled = False
56 56
57 57 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
58 58 @default('ipython_display_formatter')
59 59 def _default_formatter(self):
60 60 return IPythonDisplayFormatter(parent=self)
61 61
62 62 mimebundle_formatter = ForwardDeclaredInstance('FormatterABC')
63 63 @default('mimebundle_formatter')
64 64 def _default_mime_formatter(self):
65 65 return MimeBundleFormatter(parent=self)
66 66
67 67 # A dict of formatter whose keys are format types (MIME types) and whose
68 68 # values are subclasses of BaseFormatter.
69 69 formatters = Dict()
70 70 @default('formatters')
71 71 def _formatters_default(self):
72 72 """Activate the default formatters."""
73 73 formatter_classes = [
74 74 PlainTextFormatter,
75 75 HTMLFormatter,
76 76 MarkdownFormatter,
77 77 SVGFormatter,
78 78 PNGFormatter,
79 79 PDFFormatter,
80 80 JPEGFormatter,
81 81 LatexFormatter,
82 82 JSONFormatter,
83 83 JavascriptFormatter
84 84 ]
85 85 d = {}
86 86 for cls in formatter_classes:
87 87 f = cls(parent=self)
88 88 d[f.format_type] = f
89 89 return d
90 90
91 91 def format(self, obj, include=None, exclude=None):
92 92 """Return a format data dict for an object.
93 93
94 94 By default all format types will be computed.
95 95
96 96 The following MIME types are usually implemented:
97 97
98 98 * text/plain
99 99 * text/html
100 100 * text/markdown
101 101 * text/latex
102 102 * application/json
103 103 * application/javascript
104 104 * application/pdf
105 105 * image/png
106 106 * image/jpeg
107 107 * image/svg+xml
108 108
109 109 Parameters
110 110 ----------
111 111 obj : object
112 112 The Python object whose format data will be computed.
113 113 include : list, tuple or set; optional
114 114 A list of format type strings (MIME types) to include in the
115 115 format data dict. If this is set *only* the format types included
116 116 in this list will be computed.
117 117 exclude : list, tuple or set; optional
118 118 A list of format type string (MIME types) to exclude in the format
119 119 data dict. If this is set all format types will be computed,
120 120 except for those included in this argument.
121 121 Mimetypes present in exclude will take precedence over the ones in include
122 122
123 123 Returns
124 124 -------
125 125 (format_dict, metadata_dict) : tuple of two dicts
126 126
127 127 format_dict is a dictionary of key/value pairs, one of each format that was
128 128 generated for the object. The keys are the format types, which
129 129 will usually be MIME type strings and the values and JSON'able
130 130 data structure containing the raw data for the representation in
131 131 that format.
132 132
133 133 metadata_dict is a dictionary of metadata about each mime-type output.
134 134 Its keys will be a strict subset of the keys in format_dict.
135 135
136 136 Notes
137 137 -----
138 138
139 139 If an object implement `_repr_mimebundle_` as well as various
140 140 `_repr_*_`, the data returned by `_repr_mimebundle_` will take
141 141 precedence and the corresponding `_repr_*_` for this mimetype will
142 142 not be called.
143 143
144 144 """
145 145 format_dict = {}
146 146 md_dict = {}
147 147
148 148 if self.ipython_display_formatter(obj):
149 149 # object handled itself, don't proceed
150 150 return {}, {}
151 151
152 format_dict, md_dict = self.mimebundle_formatter(obj)
152 format_dict, md_dict = self.mimebundle_formatter(obj, include=include, exclude=exclude)
153 153
154 154 if format_dict or md_dict:
155 155 if include:
156 156 format_dict = {k:v for k,v in format_dict.items() if k in include}
157 157 md_dict = {k:v for k,v in md_dict.items() if k in include}
158 158 if exclude:
159 159 format_dict = {k:v for k,v in format_dict.items() if k not in exclude}
160 160 md_dict = {k:v for k,v in md_dict.items() if k not in exclude}
161 161
162 162 for format_type, formatter in self.formatters.items():
163 163 if format_type in format_dict:
164 164 # already got it from mimebundle, don't render again
165 165 continue
166 166 if include and format_type not in include:
167 167 continue
168 168 if exclude and format_type in exclude:
169 169 continue
170 170
171 171 md = None
172 172 try:
173 173 data = formatter(obj)
174 174 except:
175 175 # FIXME: log the exception
176 176 raise
177 177
178 178 # formatters can return raw data or (data, metadata)
179 179 if isinstance(data, tuple) and len(data) == 2:
180 180 data, md = data
181 181
182 182 if data is not None:
183 183 format_dict[format_type] = data
184 184 if md is not None:
185 185 md_dict[format_type] = md
186 186 return format_dict, md_dict
187 187
188 188 @property
189 189 def format_types(self):
190 190 """Return the format types (MIME types) of the active formatters."""
191 191 return list(self.formatters.keys())
192 192
193 193
194 194 #-----------------------------------------------------------------------------
195 195 # Formatters for specific format types (text, html, svg, etc.)
196 196 #-----------------------------------------------------------------------------
197 197
198 198
199 199 def _safe_repr(obj):
200 200 """Try to return a repr of an object
201 201
202 202 always returns a string, at least.
203 203 """
204 204 try:
205 205 return repr(obj)
206 206 except Exception as e:
207 207 return "un-repr-able object (%r)" % e
208 208
209 209
210 210 class FormatterWarning(UserWarning):
211 211 """Warning class for errors in formatters"""
212 212
213 213 @decorator
214 214 def catch_format_error(method, self, *args, **kwargs):
215 215 """show traceback on failed format call"""
216 216 try:
217 217 r = method(self, *args, **kwargs)
218 218 except NotImplementedError:
219 219 # don't warn on NotImplementedErrors
220 220 return None
221 221 except Exception:
222 222 exc_info = sys.exc_info()
223 223 ip = get_ipython()
224 224 if ip is not None:
225 225 ip.showtraceback(exc_info)
226 226 else:
227 227 traceback.print_exception(*exc_info)
228 228 return None
229 229 return self._check_return(r, args[0])
230 230
231 231
232 232 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
233 233 """ Abstract base class for Formatters.
234 234
235 235 A formatter is a callable class that is responsible for computing the
236 236 raw format data for a particular format type (MIME type). For example,
237 237 an HTML formatter would have a format type of `text/html` and would return
238 238 the HTML representation of the object when called.
239 239 """
240 240
241 241 # The format type of the data returned, usually a MIME type.
242 242 format_type = 'text/plain'
243 243
244 244 # Is the formatter enabled...
245 245 enabled = True
246 246
247 247 @abc.abstractmethod
248 248 def __call__(self, obj):
249 249 """Return a JSON'able representation of the object.
250 250
251 251 If the object cannot be formatted by this formatter,
252 252 warn and return None.
253 253 """
254 254 return repr(obj)
255 255
256 256
257 257 def _mod_name_key(typ):
258 258 """Return a (__module__, __name__) tuple for a type.
259 259
260 260 Used as key in Formatter.deferred_printers.
261 261 """
262 262 module = getattr(typ, '__module__', None)
263 263 name = getattr(typ, '__name__', None)
264 264 return (module, name)
265 265
266 266
267 267 def _get_type(obj):
268 268 """Return the type of an instance (old and new-style)"""
269 269 return getattr(obj, '__class__', None) or type(obj)
270 270
271 271
272 272 _raise_key_error = Sentinel('_raise_key_error', __name__,
273 273 """
274 274 Special value to raise a KeyError
275 275
276 276 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
277 277 """)
278 278
279 279
280 280 class BaseFormatter(Configurable):
281 281 """A base formatter class that is configurable.
282 282
283 283 This formatter should usually be used as the base class of all formatters.
284 284 It is a traited :class:`Configurable` class and includes an extensible
285 285 API for users to determine how their objects are formatted. The following
286 286 logic is used to find a function to format an given object.
287 287
288 288 1. The object is introspected to see if it has a method with the name
289 289 :attr:`print_method`. If is does, that object is passed to that method
290 290 for formatting.
291 291 2. If no print method is found, three internal dictionaries are consulted
292 292 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
293 293 and :attr:`deferred_printers`.
294 294
295 295 Users should use these dictionaries to register functions that will be
296 296 used to compute the format data for their objects (if those objects don't
297 297 have the special print methods). The easiest way of using these
298 298 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
299 299 methods.
300 300
301 301 If no function/callable is found to compute the format data, ``None`` is
302 302 returned and this format type is not used.
303 303 """
304 304
305 305 format_type = Unicode('text/plain')
306 306 _return_type = string_types
307 307
308 308 enabled = Bool(True).tag(config=True)
309 309
310 310 print_method = ObjectName('__repr__')
311 311
312 312 # The singleton printers.
313 313 # Maps the IDs of the builtin singleton objects to the format functions.
314 314 singleton_printers = Dict().tag(config=True)
315 315
316 316 # The type-specific printers.
317 317 # Map type objects to the format functions.
318 318 type_printers = Dict().tag(config=True)
319 319
320 320 # The deferred-import type-specific printers.
321 321 # Map (modulename, classname) pairs to the format functions.
322 322 deferred_printers = Dict().tag(config=True)
323 323
324 324 @catch_format_error
325 325 def __call__(self, obj):
326 326 """Compute the format for an object."""
327 327 if self.enabled:
328 328 # lookup registered printer
329 329 try:
330 330 printer = self.lookup(obj)
331 331 except KeyError:
332 332 pass
333 333 else:
334 334 return printer(obj)
335 335 # Finally look for special method names
336 336 method = get_real_method(obj, self.print_method)
337 337 if method is not None:
338 338 return method()
339 339 return None
340 340 else:
341 341 return None
342 342
343 343 def __contains__(self, typ):
344 344 """map in to lookup_by_type"""
345 345 try:
346 346 self.lookup_by_type(typ)
347 347 except KeyError:
348 348 return False
349 349 else:
350 350 return True
351 351
352 352 def _check_return(self, r, obj):
353 353 """Check that a return value is appropriate
354 354
355 355 Return the value if so, None otherwise, warning if invalid.
356 356 """
357 357 if r is None or isinstance(r, self._return_type) or \
358 358 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
359 359 return r
360 360 else:
361 361 warnings.warn(
362 362 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
363 363 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
364 364 FormatterWarning
365 365 )
366 366
367 367 def lookup(self, obj):
368 368 """Look up the formatter for a given instance.
369 369
370 370 Parameters
371 371 ----------
372 372 obj : object instance
373 373
374 374 Returns
375 375 -------
376 376 f : callable
377 377 The registered formatting callable for the type.
378 378
379 379 Raises
380 380 ------
381 381 KeyError if the type has not been registered.
382 382 """
383 383 # look for singleton first
384 384 obj_id = id(obj)
385 385 if obj_id in self.singleton_printers:
386 386 return self.singleton_printers[obj_id]
387 387 # then lookup by type
388 388 return self.lookup_by_type(_get_type(obj))
389 389
390 390 def lookup_by_type(self, typ):
391 391 """Look up the registered formatter for a type.
392 392
393 393 Parameters
394 394 ----------
395 395 typ : type or '__module__.__name__' string for a type
396 396
397 397 Returns
398 398 -------
399 399 f : callable
400 400 The registered formatting callable for the type.
401 401
402 402 Raises
403 403 ------
404 404 KeyError if the type has not been registered.
405 405 """
406 406 if isinstance(typ, string_types):
407 407 typ_key = tuple(typ.rsplit('.',1))
408 408 if typ_key not in self.deferred_printers:
409 409 # We may have it cached in the type map. We will have to
410 410 # iterate over all of the types to check.
411 411 for cls in self.type_printers:
412 412 if _mod_name_key(cls) == typ_key:
413 413 return self.type_printers[cls]
414 414 else:
415 415 return self.deferred_printers[typ_key]
416 416 else:
417 417 for cls in pretty._get_mro(typ):
418 418 if cls in self.type_printers or self._in_deferred_types(cls):
419 419 return self.type_printers[cls]
420 420
421 421 # If we have reached here, the lookup failed.
422 422 raise KeyError("No registered printer for {0!r}".format(typ))
423 423
424 424 def for_type(self, typ, func=None):
425 425 """Add a format function for a given type.
426 426
427 427 Parameters
428 428 -----------
429 429 typ : type or '__module__.__name__' string for a type
430 430 The class of the object that will be formatted using `func`.
431 431 func : callable
432 432 A callable for computing the format data.
433 433 `func` will be called with the object to be formatted,
434 434 and will return the raw data in this formatter's format.
435 435 Subclasses may use a different call signature for the
436 436 `func` argument.
437 437
438 438 If `func` is None or not specified, there will be no change,
439 439 only returning the current value.
440 440
441 441 Returns
442 442 -------
443 443 oldfunc : callable
444 444 The currently registered callable.
445 445 If you are registering a new formatter,
446 446 this will be the previous value (to enable restoring later).
447 447 """
448 448 # if string given, interpret as 'pkg.module.class_name'
449 449 if isinstance(typ, string_types):
450 450 type_module, type_name = typ.rsplit('.', 1)
451 451 return self.for_type_by_name(type_module, type_name, func)
452 452
453 453 try:
454 454 oldfunc = self.lookup_by_type(typ)
455 455 except KeyError:
456 456 oldfunc = None
457 457
458 458 if func is not None:
459 459 self.type_printers[typ] = func
460 460
461 461 return oldfunc
462 462
463 463 def for_type_by_name(self, type_module, type_name, func=None):
464 464 """Add a format function for a type specified by the full dotted
465 465 module and name of the type, rather than the type of the object.
466 466
467 467 Parameters
468 468 ----------
469 469 type_module : str
470 470 The full dotted name of the module the type is defined in, like
471 471 ``numpy``.
472 472 type_name : str
473 473 The name of the type (the class name), like ``dtype``
474 474 func : callable
475 475 A callable for computing the format data.
476 476 `func` will be called with the object to be formatted,
477 477 and will return the raw data in this formatter's format.
478 478 Subclasses may use a different call signature for the
479 479 `func` argument.
480 480
481 481 If `func` is None or unspecified, there will be no change,
482 482 only returning the current value.
483 483
484 484 Returns
485 485 -------
486 486 oldfunc : callable
487 487 The currently registered callable.
488 488 If you are registering a new formatter,
489 489 this will be the previous value (to enable restoring later).
490 490 """
491 491 key = (type_module, type_name)
492 492
493 493 try:
494 494 oldfunc = self.lookup_by_type("%s.%s" % key)
495 495 except KeyError:
496 496 oldfunc = None
497 497
498 498 if func is not None:
499 499 self.deferred_printers[key] = func
500 500 return oldfunc
501 501
502 502 def pop(self, typ, default=_raise_key_error):
503 503 """Pop a formatter for the given type.
504 504
505 505 Parameters
506 506 ----------
507 507 typ : type or '__module__.__name__' string for a type
508 508 default : object
509 509 value to be returned if no formatter is registered for typ.
510 510
511 511 Returns
512 512 -------
513 513 obj : object
514 514 The last registered object for the type.
515 515
516 516 Raises
517 517 ------
518 518 KeyError if the type is not registered and default is not specified.
519 519 """
520 520
521 521 if isinstance(typ, string_types):
522 522 typ_key = tuple(typ.rsplit('.',1))
523 523 if typ_key not in self.deferred_printers:
524 524 # We may have it cached in the type map. We will have to
525 525 # iterate over all of the types to check.
526 526 for cls in self.type_printers:
527 527 if _mod_name_key(cls) == typ_key:
528 528 old = self.type_printers.pop(cls)
529 529 break
530 530 else:
531 531 old = default
532 532 else:
533 533 old = self.deferred_printers.pop(typ_key)
534 534 else:
535 535 if typ in self.type_printers:
536 536 old = self.type_printers.pop(typ)
537 537 else:
538 538 old = self.deferred_printers.pop(_mod_name_key(typ), default)
539 539 if old is _raise_key_error:
540 540 raise KeyError("No registered value for {0!r}".format(typ))
541 541 return old
542 542
543 543 def _in_deferred_types(self, cls):
544 544 """
545 545 Check if the given class is specified in the deferred type registry.
546 546
547 547 Successful matches will be moved to the regular type registry for future use.
548 548 """
549 549 mod = getattr(cls, '__module__', None)
550 550 name = getattr(cls, '__name__', None)
551 551 key = (mod, name)
552 552 if key in self.deferred_printers:
553 553 # Move the printer over to the regular registry.
554 554 printer = self.deferred_printers.pop(key)
555 555 self.type_printers[cls] = printer
556 556 return True
557 557 return False
558 558
559 559
560 560 class PlainTextFormatter(BaseFormatter):
561 561 """The default pretty-printer.
562 562
563 563 This uses :mod:`IPython.lib.pretty` to compute the format data of
564 564 the object. If the object cannot be pretty printed, :func:`repr` is used.
565 565 See the documentation of :mod:`IPython.lib.pretty` for details on
566 566 how to write pretty printers. Here is a simple example::
567 567
568 568 def dtype_pprinter(obj, p, cycle):
569 569 if cycle:
570 570 return p.text('dtype(...)')
571 571 if hasattr(obj, 'fields'):
572 572 if obj.fields is None:
573 573 p.text(repr(obj))
574 574 else:
575 575 p.begin_group(7, 'dtype([')
576 576 for i, field in enumerate(obj.descr):
577 577 if i > 0:
578 578 p.text(',')
579 579 p.breakable()
580 580 p.pretty(field)
581 581 p.end_group(7, '])')
582 582 """
583 583
584 584 # The format type of data returned.
585 585 format_type = Unicode('text/plain')
586 586
587 587 # This subclass ignores this attribute as it always need to return
588 588 # something.
589 589 enabled = Bool(True).tag(config=False)
590 590
591 591 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
592 592 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
593 593
594 594 Set to 0 to disable truncation.
595 595 """
596 596 ).tag(config=True)
597 597
598 598 # Look for a _repr_pretty_ methods to use for pretty printing.
599 599 print_method = ObjectName('_repr_pretty_')
600 600
601 601 # Whether to pretty-print or not.
602 602 pprint = Bool(True).tag(config=True)
603 603
604 604 # Whether to be verbose or not.
605 605 verbose = Bool(False).tag(config=True)
606 606
607 607 # The maximum width.
608 608 max_width = Integer(79).tag(config=True)
609 609
610 610 # The newline character.
611 611 newline = Unicode('\n').tag(config=True)
612 612
613 613 # format-string for pprinting floats
614 614 float_format = Unicode('%r')
615 615 # setter for float precision, either int or direct format-string
616 616 float_precision = CUnicode('').tag(config=True)
617 617
618 618 @observe('float_precision')
619 619 def _float_precision_changed(self, change):
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 new = change['new']
634 634 if '%' in new:
635 635 # got explicit format string
636 636 fmt = new
637 637 try:
638 638 fmt%3.14159
639 639 except Exception:
640 640 raise ValueError("Precision must be int or format string, not %r"%new)
641 641 elif new:
642 642 # otherwise, should be an int
643 643 try:
644 644 i = int(new)
645 645 assert i >= 0
646 646 except ValueError:
647 647 raise ValueError("Precision must be int or format string, not %r"%new)
648 648 except AssertionError:
649 649 raise ValueError("int precision must be non-negative, not %r"%i)
650 650
651 651 fmt = '%%.%if'%i
652 652 if 'numpy' in sys.modules:
653 653 # set numpy precision if it has been imported
654 654 import numpy
655 655 numpy.set_printoptions(precision=i)
656 656 else:
657 657 # default back to repr
658 658 fmt = '%r'
659 659 if 'numpy' in sys.modules:
660 660 import numpy
661 661 # numpy default is 8
662 662 numpy.set_printoptions(precision=8)
663 663 self.float_format = fmt
664 664
665 665 # Use the default pretty printers from IPython.lib.pretty.
666 666 @default('singleton_printers')
667 667 def _singleton_printers_default(self):
668 668 return pretty._singleton_pprinters.copy()
669 669
670 670 @default('type_printers')
671 671 def _type_printers_default(self):
672 672 d = pretty._type_pprinters.copy()
673 673 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
674 674 return d
675 675
676 676 @default('deferred_printers')
677 677 def _deferred_printers_default(self):
678 678 return pretty._deferred_type_pprinters.copy()
679 679
680 680 #### FormatterABC interface ####
681 681
682 682 @catch_format_error
683 683 def __call__(self, obj):
684 684 """Compute the pretty representation of the object."""
685 685 if not self.pprint:
686 686 return repr(obj)
687 687 else:
688 688 # handle str and unicode on Python 2
689 689 # io.StringIO only accepts unicode,
690 690 # cStringIO doesn't handle unicode on py2,
691 691 # StringIO allows str, unicode but only ascii str
692 692 stream = pretty.CUnicodeIO()
693 693 printer = pretty.RepresentationPrinter(stream, self.verbose,
694 694 self.max_width, self.newline,
695 695 max_seq_length=self.max_seq_length,
696 696 singleton_pprinters=self.singleton_printers,
697 697 type_pprinters=self.type_printers,
698 698 deferred_pprinters=self.deferred_printers)
699 699 printer.pretty(obj)
700 700 printer.flush()
701 701 return stream.getvalue()
702 702
703 703
704 704 class HTMLFormatter(BaseFormatter):
705 705 """An HTML formatter.
706 706
707 707 To define the callables that compute the HTML representation of your
708 708 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
709 709 or :meth:`for_type_by_name` methods to register functions that handle
710 710 this.
711 711
712 712 The return value of this formatter should be a valid HTML snippet that
713 713 could be injected into an existing DOM. It should *not* include the
714 714 ```<html>`` or ```<body>`` tags.
715 715 """
716 716 format_type = Unicode('text/html')
717 717
718 718 print_method = ObjectName('_repr_html_')
719 719
720 720
721 721 class MarkdownFormatter(BaseFormatter):
722 722 """A Markdown formatter.
723 723
724 724 To define the callables that compute the Markdown representation of your
725 725 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
726 726 or :meth:`for_type_by_name` methods to register functions that handle
727 727 this.
728 728
729 729 The return value of this formatter should be a valid Markdown.
730 730 """
731 731 format_type = Unicode('text/markdown')
732 732
733 733 print_method = ObjectName('_repr_markdown_')
734 734
735 735 class SVGFormatter(BaseFormatter):
736 736 """An SVG formatter.
737 737
738 738 To define the callables that compute the SVG representation of your
739 739 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
740 740 or :meth:`for_type_by_name` methods to register functions that handle
741 741 this.
742 742
743 743 The return value of this formatter should be valid SVG enclosed in
744 744 ```<svg>``` tags, that could be injected into an existing DOM. It should
745 745 *not* include the ```<html>`` or ```<body>`` tags.
746 746 """
747 747 format_type = Unicode('image/svg+xml')
748 748
749 749 print_method = ObjectName('_repr_svg_')
750 750
751 751
752 752 class PNGFormatter(BaseFormatter):
753 753 """A PNG formatter.
754 754
755 755 To define the callables that compute the PNG representation of your
756 756 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
757 757 or :meth:`for_type_by_name` methods to register functions that handle
758 758 this.
759 759
760 760 The return value of this formatter should be raw PNG data, *not*
761 761 base64 encoded.
762 762 """
763 763 format_type = Unicode('image/png')
764 764
765 765 print_method = ObjectName('_repr_png_')
766 766
767 767 _return_type = (bytes, unicode_type)
768 768
769 769
770 770 class JPEGFormatter(BaseFormatter):
771 771 """A JPEG formatter.
772 772
773 773 To define the callables that compute the JPEG representation of your
774 774 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
775 775 or :meth:`for_type_by_name` methods to register functions that handle
776 776 this.
777 777
778 778 The return value of this formatter should be raw JPEG data, *not*
779 779 base64 encoded.
780 780 """
781 781 format_type = Unicode('image/jpeg')
782 782
783 783 print_method = ObjectName('_repr_jpeg_')
784 784
785 785 _return_type = (bytes, unicode_type)
786 786
787 787
788 788 class LatexFormatter(BaseFormatter):
789 789 """A LaTeX formatter.
790 790
791 791 To define the callables that compute the LaTeX representation of your
792 792 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
793 793 or :meth:`for_type_by_name` methods to register functions that handle
794 794 this.
795 795
796 796 The return value of this formatter should be a valid LaTeX equation,
797 797 enclosed in either ```$```, ```$$``` or another LaTeX equation
798 798 environment.
799 799 """
800 800 format_type = Unicode('text/latex')
801 801
802 802 print_method = ObjectName('_repr_latex_')
803 803
804 804
805 805 class JSONFormatter(BaseFormatter):
806 806 """A JSON string formatter.
807 807
808 808 To define the callables that compute the JSONable representation of
809 809 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
810 810 or :meth:`for_type_by_name` methods to register functions that handle
811 811 this.
812 812
813 813 The return value of this formatter should be a JSONable list or dict.
814 814 JSON scalars (None, number, string) are not allowed, only dict or list containers.
815 815 """
816 816 format_type = Unicode('application/json')
817 817 _return_type = (list, dict)
818 818
819 819 print_method = ObjectName('_repr_json_')
820 820
821 821 def _check_return(self, r, obj):
822 822 """Check that a return value is appropriate
823 823
824 824 Return the value if so, None otherwise, warning if invalid.
825 825 """
826 826 if r is None:
827 827 return
828 828 md = None
829 829 if isinstance(r, tuple):
830 830 # unpack data, metadata tuple for type checking on first element
831 831 r, md = r
832 832
833 833 # handle deprecated JSON-as-string form from IPython < 3
834 834 if isinstance(r, string_types):
835 835 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
836 836 FormatterWarning)
837 837 r = json.loads(r)
838 838
839 839 if md is not None:
840 840 # put the tuple back together
841 841 r = (r, md)
842 842 return super(JSONFormatter, self)._check_return(r, obj)
843 843
844 844
845 845 class JavascriptFormatter(BaseFormatter):
846 846 """A Javascript formatter.
847 847
848 848 To define the callables that compute the Javascript representation of
849 849 your objects, define a :meth:`_repr_javascript_` method or use the
850 850 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
851 851 that handle this.
852 852
853 853 The return value of this formatter should be valid Javascript code and
854 854 should *not* be enclosed in ```<script>``` tags.
855 855 """
856 856 format_type = Unicode('application/javascript')
857 857
858 858 print_method = ObjectName('_repr_javascript_')
859 859
860 860
861 861 class PDFFormatter(BaseFormatter):
862 862 """A PDF formatter.
863 863
864 864 To define the callables that compute the PDF representation of your
865 865 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
866 866 or :meth:`for_type_by_name` methods to register functions that handle
867 867 this.
868 868
869 869 The return value of this formatter should be raw PDF data, *not*
870 870 base64 encoded.
871 871 """
872 872 format_type = Unicode('application/pdf')
873 873
874 874 print_method = ObjectName('_repr_pdf_')
875 875
876 876 _return_type = (bytes, unicode_type)
877 877
878 878 class IPythonDisplayFormatter(BaseFormatter):
879 879 """An escape-hatch Formatter for objects that know how to display themselves.
880 880
881 881 To define the callables that compute the representation of your
882 882 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
883 883 or :meth:`for_type_by_name` methods to register functions that handle
884 884 this. Unlike mime-type displays, this method should not return anything,
885 885 instead calling any appropriate display methods itself.
886 886
887 887 This display formatter has highest priority.
888 888 If it fires, no other display formatter will be called.
889 889
890 890 Prior to IPython 6.1, `_ipython_display_` was the only way to display custom mime-types
891 891 without registering a new Formatter.
892 892
893 893 IPython 6.1 introduces `_repr_mimebundle_` for displaying custom mime-types,
894 894 so `_ipython_display_` should only be used for objects that require unusual
895 895 display patterns, such as multiple display calls.
896 896 """
897 897 print_method = ObjectName('_ipython_display_')
898 898 _return_type = (type(None), bool)
899 899
900 900 @catch_format_error
901 901 def __call__(self, obj):
902 902 """Compute the format for an object."""
903 903 if self.enabled:
904 904 # lookup registered printer
905 905 try:
906 906 printer = self.lookup(obj)
907 907 except KeyError:
908 908 pass
909 909 else:
910 910 printer(obj)
911 911 return True
912 912 # Finally look for special method names
913 913 method = get_real_method(obj, self.print_method)
914 914 if method is not None:
915 915 method()
916 916 return True
917 917
918 918
919 919 class MimeBundleFormatter(BaseFormatter):
920 920 """A Formatter for arbitrary mime-types.
921 921
922 922 Unlike other `_repr_<mimetype>_` methods,
923 923 `_repr_mimebundle_` should return mime-bundle data,
924 924 either the mime-keyed `data` dictionary or the tuple `(data, metadata)`.
925 925 Any mime-type is valid.
926 926
927 927 To define the callables that compute the mime-bundle representation of your
928 928 objects, define a :meth:`_repr_mimebundle_` method or use the :meth:`for_type`
929 929 or :meth:`for_type_by_name` methods to register functions that handle
930 930 this.
931 931
932 932 .. versionadded:: 6.1
933 933 """
934 934 print_method = ObjectName('_repr_mimebundle_')
935 935 _return_type = dict
936 936
937 937 def _check_return(self, r, obj):
938 938 r = super(MimeBundleFormatter, self)._check_return(r, obj)
939 939 # always return (data, metadata):
940 940 if r is None:
941 941 return {}, {}
942 942 if not isinstance(r, tuple):
943 943 return r, {}
944 944 return r
945 945
946 @catch_format_error
947 def __call__(self, obj, include=None, exclude=None):
948 """Compute the format for an object.
949
950 Identical to parent's method but we pass extra parameters to the method.
951
952 Unlike other _repr_*_ `_repr_mimebundle_` should allow extra kwargs, in
953 particular `include` and `exclude`.
954 """
955 if self.enabled:
956 # lookup registered printer
957 try:
958 printer = self.lookup(obj)
959 except KeyError:
960 pass
961 else:
962 return printer(obj)
963 # Finally look for special method names
964 method = get_real_method(obj, self.print_method)
965
966 if method is not None:
967 d = {}
968 d['include'] = include
969 d['exclude'] = include
970 return method(**d)
971 return None
972 else:
973 return None
974
946 975
947 976 FormatterABC.register(BaseFormatter)
948 977 FormatterABC.register(PlainTextFormatter)
949 978 FormatterABC.register(HTMLFormatter)
950 979 FormatterABC.register(MarkdownFormatter)
951 980 FormatterABC.register(SVGFormatter)
952 981 FormatterABC.register(PNGFormatter)
953 982 FormatterABC.register(PDFFormatter)
954 983 FormatterABC.register(JPEGFormatter)
955 984 FormatterABC.register(LatexFormatter)
956 985 FormatterABC.register(JSONFormatter)
957 986 FormatterABC.register(JavascriptFormatter)
958 987 FormatterABC.register(IPythonDisplayFormatter)
959 988 FormatterABC.register(MimeBundleFormatter)
960 989
961 990
962 991 def format_display_data(obj, include=None, exclude=None):
963 992 """Return a format data dict for an object.
964 993
965 994 By default all format types will be computed.
966 995
967 996 The following MIME types are currently implemented:
968 997
969 998 * text/plain
970 999 * text/html
971 1000 * text/markdown
972 1001 * text/latex
973 1002 * application/json
974 1003 * application/javascript
975 1004 * application/pdf
976 1005 * image/png
977 1006 * image/jpeg
978 1007 * image/svg+xml
979 1008
980 1009 Parameters
981 1010 ----------
982 1011 obj : object
983 1012 The Python object whose format data will be computed.
984 1013
985 1014 Returns
986 1015 -------
987 1016 format_dict : dict
988 1017 A dictionary of key/value pairs, one or each format that was
989 1018 generated for the object. The keys are the format types, which
990 1019 will usually be MIME type strings and the values and JSON'able
991 1020 data structure containing the raw data for the representation in
992 1021 that format.
993 1022 include : list or tuple, optional
994 1023 A list of format type strings (MIME types) to include in the
995 1024 format data dict. If this is set *only* the format types included
996 1025 in this list will be computed.
997 1026 exclude : list or tuple, optional
998 1027 A list of format type string (MIME types) to exclue in the format
999 1028 data dict. If this is set all format types will be computed,
1000 1029 except for those included in this argument.
1001 1030 """
1002 1031 from IPython.core.interactiveshell import InteractiveShell
1003 1032
1004 1033 return InteractiveShell.instance().display_formatter.format(
1005 1034 obj,
1006 1035 include,
1007 1036 exclude
1008 1037 )
@@ -1,503 +1,503 b''
1 1 """Tests for the Formatters."""
2 2
3 3 import warnings
4 4 from math import pi
5 5
6 6 try:
7 7 import numpy
8 8 except:
9 9 numpy = None
10 10 import nose.tools as nt
11 11
12 12 from IPython import get_ipython
13 13 from traitlets.config import Config
14 14 from IPython.core.formatters import (
15 15 PlainTextFormatter, HTMLFormatter, PDFFormatter, _mod_name_key,
16 16 DisplayFormatter, JSONFormatter,
17 17 )
18 18 from IPython.utils.io import capture_output
19 19
20 20 class A(object):
21 21 def __repr__(self):
22 22 return 'A()'
23 23
24 24 class B(A):
25 25 def __repr__(self):
26 26 return 'B()'
27 27
28 28 class C:
29 29 pass
30 30
31 31 class BadRepr(object):
32 32 def __repr__(self):
33 33 raise ValueError("bad repr")
34 34
35 35 class BadPretty(object):
36 36 _repr_pretty_ = None
37 37
38 38 class GoodPretty(object):
39 39 def _repr_pretty_(self, pp, cycle):
40 40 pp.text('foo')
41 41
42 42 def __repr__(self):
43 43 return 'GoodPretty()'
44 44
45 45 def foo_printer(obj, pp, cycle):
46 46 pp.text('foo')
47 47
48 48 def test_pretty():
49 49 f = PlainTextFormatter()
50 50 f.for_type(A, foo_printer)
51 51 nt.assert_equal(f(A()), 'foo')
52 52 nt.assert_equal(f(B()), 'foo')
53 53 nt.assert_equal(f(GoodPretty()), 'foo')
54 54 # Just don't raise an exception for the following:
55 55 f(BadPretty())
56 56
57 57 f.pprint = False
58 58 nt.assert_equal(f(A()), 'A()')
59 59 nt.assert_equal(f(B()), 'B()')
60 60 nt.assert_equal(f(GoodPretty()), 'GoodPretty()')
61 61
62 62
63 63 def test_deferred():
64 64 f = PlainTextFormatter()
65 65
66 66 def test_precision():
67 67 """test various values for float_precision."""
68 68 f = PlainTextFormatter()
69 69 nt.assert_equal(f(pi), repr(pi))
70 70 f.float_precision = 0
71 71 if numpy:
72 72 po = numpy.get_printoptions()
73 73 nt.assert_equal(po['precision'], 0)
74 74 nt.assert_equal(f(pi), '3')
75 75 f.float_precision = 2
76 76 if numpy:
77 77 po = numpy.get_printoptions()
78 78 nt.assert_equal(po['precision'], 2)
79 79 nt.assert_equal(f(pi), '3.14')
80 80 f.float_precision = '%g'
81 81 if numpy:
82 82 po = numpy.get_printoptions()
83 83 nt.assert_equal(po['precision'], 2)
84 84 nt.assert_equal(f(pi), '3.14159')
85 85 f.float_precision = '%e'
86 86 nt.assert_equal(f(pi), '3.141593e+00')
87 87 f.float_precision = ''
88 88 if numpy:
89 89 po = numpy.get_printoptions()
90 90 nt.assert_equal(po['precision'], 8)
91 91 nt.assert_equal(f(pi), repr(pi))
92 92
93 93 def test_bad_precision():
94 94 """test various invalid values for float_precision."""
95 95 f = PlainTextFormatter()
96 96 def set_fp(p):
97 97 f.float_precision=p
98 98 nt.assert_raises(ValueError, set_fp, '%')
99 99 nt.assert_raises(ValueError, set_fp, '%.3f%i')
100 100 nt.assert_raises(ValueError, set_fp, 'foo')
101 101 nt.assert_raises(ValueError, set_fp, -1)
102 102
103 103 def test_for_type():
104 104 f = PlainTextFormatter()
105 105
106 106 # initial return, None
107 107 nt.assert_is(f.for_type(C, foo_printer), None)
108 108 # no func queries
109 109 nt.assert_is(f.for_type(C), foo_printer)
110 110 # shouldn't change anything
111 111 nt.assert_is(f.for_type(C), foo_printer)
112 112 # None should do the same
113 113 nt.assert_is(f.for_type(C, None), foo_printer)
114 114 nt.assert_is(f.for_type(C, None), foo_printer)
115 115
116 116 def test_for_type_string():
117 117 f = PlainTextFormatter()
118 118
119 119 mod = C.__module__
120 120
121 121 type_str = '%s.%s' % (C.__module__, 'C')
122 122
123 123 # initial return, None
124 124 nt.assert_is(f.for_type(type_str, foo_printer), None)
125 125 # no func queries
126 126 nt.assert_is(f.for_type(type_str), foo_printer)
127 127 nt.assert_in(_mod_name_key(C), f.deferred_printers)
128 128 nt.assert_is(f.for_type(C), foo_printer)
129 129 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
130 130 nt.assert_in(C, f.type_printers)
131 131
132 132 def test_for_type_by_name():
133 133 f = PlainTextFormatter()
134 134
135 135 mod = C.__module__
136 136
137 137 # initial return, None
138 138 nt.assert_is(f.for_type_by_name(mod, 'C', foo_printer), None)
139 139 # no func queries
140 140 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
141 141 # shouldn't change anything
142 142 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
143 143 # None should do the same
144 144 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
145 145 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
146 146
147 147 def test_lookup():
148 148 f = PlainTextFormatter()
149 149
150 150 f.for_type(C, foo_printer)
151 151 nt.assert_is(f.lookup(C()), foo_printer)
152 152 with nt.assert_raises(KeyError):
153 153 f.lookup(A())
154 154
155 155 def test_lookup_string():
156 156 f = PlainTextFormatter()
157 157 type_str = '%s.%s' % (C.__module__, 'C')
158 158
159 159 f.for_type(type_str, foo_printer)
160 160 nt.assert_is(f.lookup(C()), foo_printer)
161 161 # should move from deferred to imported dict
162 162 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
163 163 nt.assert_in(C, f.type_printers)
164 164
165 165 def test_lookup_by_type():
166 166 f = PlainTextFormatter()
167 167 f.for_type(C, foo_printer)
168 168 nt.assert_is(f.lookup_by_type(C), foo_printer)
169 169 type_str = '%s.%s' % (C.__module__, 'C')
170 170 with nt.assert_raises(KeyError):
171 171 f.lookup_by_type(A)
172 172
173 173 def test_lookup_by_type_string():
174 174 f = PlainTextFormatter()
175 175 type_str = '%s.%s' % (C.__module__, 'C')
176 176 f.for_type(type_str, foo_printer)
177 177
178 178 # verify insertion
179 179 nt.assert_in(_mod_name_key(C), f.deferred_printers)
180 180 nt.assert_not_in(C, f.type_printers)
181 181
182 182 nt.assert_is(f.lookup_by_type(type_str), foo_printer)
183 183 # lookup by string doesn't cause import
184 184 nt.assert_in(_mod_name_key(C), f.deferred_printers)
185 185 nt.assert_not_in(C, f.type_printers)
186 186
187 187 nt.assert_is(f.lookup_by_type(C), foo_printer)
188 188 # should move from deferred to imported dict
189 189 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
190 190 nt.assert_in(C, f.type_printers)
191 191
192 192 def test_in_formatter():
193 193 f = PlainTextFormatter()
194 194 f.for_type(C, foo_printer)
195 195 type_str = '%s.%s' % (C.__module__, 'C')
196 196 nt.assert_in(C, f)
197 197 nt.assert_in(type_str, f)
198 198
199 199 def test_string_in_formatter():
200 200 f = PlainTextFormatter()
201 201 type_str = '%s.%s' % (C.__module__, 'C')
202 202 f.for_type(type_str, foo_printer)
203 203 nt.assert_in(type_str, f)
204 204 nt.assert_in(C, f)
205 205
206 206 def test_pop():
207 207 f = PlainTextFormatter()
208 208 f.for_type(C, foo_printer)
209 209 nt.assert_is(f.lookup_by_type(C), foo_printer)
210 210 nt.assert_is(f.pop(C, None), foo_printer)
211 211 f.for_type(C, foo_printer)
212 212 nt.assert_is(f.pop(C), foo_printer)
213 213 with nt.assert_raises(KeyError):
214 214 f.lookup_by_type(C)
215 215 with nt.assert_raises(KeyError):
216 216 f.pop(C)
217 217 with nt.assert_raises(KeyError):
218 218 f.pop(A)
219 219 nt.assert_is(f.pop(A, None), None)
220 220
221 221 def test_pop_string():
222 222 f = PlainTextFormatter()
223 223 type_str = '%s.%s' % (C.__module__, 'C')
224 224
225 225 with nt.assert_raises(KeyError):
226 226 f.pop(type_str)
227 227
228 228 f.for_type(type_str, foo_printer)
229 229 f.pop(type_str)
230 230 with nt.assert_raises(KeyError):
231 231 f.lookup_by_type(C)
232 232 with nt.assert_raises(KeyError):
233 233 f.pop(type_str)
234 234
235 235 f.for_type(C, foo_printer)
236 236 nt.assert_is(f.pop(type_str, None), foo_printer)
237 237 with nt.assert_raises(KeyError):
238 238 f.lookup_by_type(C)
239 239 with nt.assert_raises(KeyError):
240 240 f.pop(type_str)
241 241 nt.assert_is(f.pop(type_str, None), None)
242 242
243 243
244 244 def test_error_method():
245 245 f = HTMLFormatter()
246 246 class BadHTML(object):
247 247 def _repr_html_(self):
248 248 raise ValueError("Bad HTML")
249 249 bad = BadHTML()
250 250 with capture_output() as captured:
251 251 result = f(bad)
252 252 nt.assert_is(result, None)
253 253 nt.assert_in("Traceback", captured.stdout)
254 254 nt.assert_in("Bad HTML", captured.stdout)
255 255 nt.assert_in("_repr_html_", captured.stdout)
256 256
257 257 def test_nowarn_notimplemented():
258 258 f = HTMLFormatter()
259 259 class HTMLNotImplemented(object):
260 260 def _repr_html_(self):
261 261 raise NotImplementedError
262 262 h = HTMLNotImplemented()
263 263 with capture_output() as captured:
264 264 result = f(h)
265 265 nt.assert_is(result, None)
266 266 nt.assert_equal("", captured.stderr)
267 267 nt.assert_equal("", captured.stdout)
268 268
269 269 def test_warn_error_for_type():
270 270 f = HTMLFormatter()
271 271 f.for_type(int, lambda i: name_error)
272 272 with capture_output() as captured:
273 273 result = f(5)
274 274 nt.assert_is(result, None)
275 275 nt.assert_in("Traceback", captured.stdout)
276 276 nt.assert_in("NameError", captured.stdout)
277 277 nt.assert_in("name_error", captured.stdout)
278 278
279 279 def test_error_pretty_method():
280 280 f = PlainTextFormatter()
281 281 class BadPretty(object):
282 282 def _repr_pretty_(self):
283 283 return "hello"
284 284 bad = BadPretty()
285 285 with capture_output() as captured:
286 286 result = f(bad)
287 287 nt.assert_is(result, None)
288 288 nt.assert_in("Traceback", captured.stdout)
289 289 nt.assert_in("_repr_pretty_", captured.stdout)
290 290 nt.assert_in("given", captured.stdout)
291 291 nt.assert_in("argument", captured.stdout)
292 292
293 293
294 294 def test_bad_repr_traceback():
295 295 f = PlainTextFormatter()
296 296 bad = BadRepr()
297 297 with capture_output() as captured:
298 298 result = f(bad)
299 299 # catches error, returns None
300 300 nt.assert_is(result, None)
301 301 nt.assert_in("Traceback", captured.stdout)
302 302 nt.assert_in("__repr__", captured.stdout)
303 303 nt.assert_in("ValueError", captured.stdout)
304 304
305 305
306 306 class MakePDF(object):
307 307 def _repr_pdf_(self):
308 308 return 'PDF'
309 309
310 310 def test_pdf_formatter():
311 311 pdf = MakePDF()
312 312 f = PDFFormatter()
313 313 nt.assert_equal(f(pdf), 'PDF')
314 314
315 315 def test_print_method_bound():
316 316 f = HTMLFormatter()
317 317 class MyHTML(object):
318 318 def _repr_html_(self):
319 319 return "hello"
320 320 with capture_output() as captured:
321 321 result = f(MyHTML)
322 322 nt.assert_is(result, None)
323 323 nt.assert_not_in("FormatterWarning", captured.stderr)
324 324
325 325 with capture_output() as captured:
326 326 result = f(MyHTML())
327 327 nt.assert_equal(result, "hello")
328 328 nt.assert_equal(captured.stderr, "")
329 329
330 330 def test_print_method_weird():
331 331
332 332 class TextMagicHat(object):
333 333 def __getattr__(self, key):
334 334 return key
335 335
336 336 f = HTMLFormatter()
337 337
338 338 text_hat = TextMagicHat()
339 339 nt.assert_equal(text_hat._repr_html_, '_repr_html_')
340 340 with capture_output() as captured:
341 341 result = f(text_hat)
342 342
343 343 nt.assert_is(result, None)
344 344 nt.assert_not_in("FormatterWarning", captured.stderr)
345 345
346 346 class CallableMagicHat(object):
347 347 def __getattr__(self, key):
348 348 return lambda : key
349 349
350 350 call_hat = CallableMagicHat()
351 351 with capture_output() as captured:
352 352 result = f(call_hat)
353 353
354 354 nt.assert_equal(result, None)
355 355
356 356 class BadReprArgs(object):
357 357 def _repr_html_(self, extra, args):
358 358 return "html"
359 359
360 360 bad = BadReprArgs()
361 361 with capture_output() as captured:
362 362 result = f(bad)
363 363
364 364 nt.assert_is(result, None)
365 365 nt.assert_not_in("FormatterWarning", captured.stderr)
366 366
367 367
368 368 def test_format_config():
369 369 """config objects don't pretend to support fancy reprs with lazy attrs"""
370 370 f = HTMLFormatter()
371 371 cfg = Config()
372 372 with capture_output() as captured:
373 373 result = f(cfg)
374 374 nt.assert_is(result, None)
375 375 nt.assert_equal(captured.stderr, "")
376 376
377 377 with capture_output() as captured:
378 378 result = f(Config)
379 379 nt.assert_is(result, None)
380 380 nt.assert_equal(captured.stderr, "")
381 381
382 382 def test_pretty_max_seq_length():
383 383 f = PlainTextFormatter(max_seq_length=1)
384 384 lis = list(range(3))
385 385 text = f(lis)
386 386 nt.assert_equal(text, '[0, ...]')
387 387 f.max_seq_length = 0
388 388 text = f(lis)
389 389 nt.assert_equal(text, '[0, 1, 2]')
390 390 text = f(list(range(1024)))
391 391 lines = text.splitlines()
392 392 nt.assert_equal(len(lines), 1024)
393 393
394 394
395 395 def test_ipython_display_formatter():
396 396 """Objects with _ipython_display_ defined bypass other formatters"""
397 397 f = get_ipython().display_formatter
398 398 catcher = []
399 399 class SelfDisplaying(object):
400 400 def _ipython_display_(self):
401 401 catcher.append(self)
402 402
403 403 class NotSelfDisplaying(object):
404 404 def __repr__(self):
405 405 return "NotSelfDisplaying"
406 406
407 407 def _ipython_display_(self):
408 408 raise NotImplementedError
409 409
410 410 save_enabled = f.ipython_display_formatter.enabled
411 411 f.ipython_display_formatter.enabled = True
412 412
413 413 yes = SelfDisplaying()
414 414 no = NotSelfDisplaying()
415 415
416 416 d, md = f.format(no)
417 417 nt.assert_equal(d, {'text/plain': repr(no)})
418 418 nt.assert_equal(md, {})
419 419 nt.assert_equal(catcher, [])
420 420
421 421 d, md = f.format(yes)
422 422 nt.assert_equal(d, {})
423 423 nt.assert_equal(md, {})
424 424 nt.assert_equal(catcher, [yes])
425 425
426 426 f.ipython_display_formatter.enabled = save_enabled
427 427
428 428
429 429 def test_json_as_string_deprecated():
430 430 class JSONString(object):
431 431 def _repr_json_(self):
432 432 return '{}'
433 433
434 434 f = JSONFormatter()
435 435 with warnings.catch_warnings(record=True) as w:
436 436 d = f(JSONString())
437 437 nt.assert_equal(d, {})
438 438 nt.assert_equal(len(w), 1)
439 439
440 440
441 441 def test_repr_mime():
442 442 class HasReprMime(object):
443 def _repr_mimebundle_(self):
443 def _repr_mimebundle_(self, include=None, exclude=None):
444 444 return {
445 445 'application/json+test.v2': {
446 446 'x': 'y'
447 447 },
448 448 'plain/text' : '<HasReprMime>',
449 449 'image/png' : 'i-overwrite'
450 450 }
451 451
452 452 def _repr_png_(self):
453 453 return 'should-be-overwritten'
454 454 def _repr_html_(self):
455 455 return '<b>hi!</b>'
456 456
457 457 f = get_ipython().display_formatter
458 458 html_f = f.formatters['text/html']
459 459 save_enabled = html_f.enabled
460 460 html_f.enabled = True
461 461 obj = HasReprMime()
462 462 d, md = f.format(obj)
463 463 html_f.enabled = save_enabled
464 464
465 465 nt.assert_equal(sorted(d), ['application/json+test.v2',
466 466 'image/png',
467 467 'plain/text',
468 468 'text/html',
469 469 'text/plain'])
470 470 nt.assert_equal(md, {})
471 471
472 472 d, md = f.format(obj, include={'image/png'})
473 473 nt.assert_equal(list(d.keys()), ['image/png'],
474 474 'Include should filter out even things from repr_mimebundle')
475 475 nt.assert_equal(d['image/png'], 'i-overwrite', '_repr_mimebundle_ take precedence')
476 476
477 477
478 478 def test_repr_mime_meta():
479 479 class HasReprMimeMeta(object):
480 def _repr_mimebundle_(self):
480 def _repr_mimebundle_(self, include=None, exclude=None):
481 481 data = {
482 482 'image/png': 'base64-image-data',
483 483 }
484 484 metadata = {
485 485 'image/png': {
486 486 'width': 5,
487 487 'height': 10,
488 488 }
489 489 }
490 490 return (data, metadata)
491 491
492 492 f = get_ipython().display_formatter
493 493 obj = HasReprMimeMeta()
494 494 d, md = f.format(obj)
495 495 nt.assert_equal(sorted(d), ['image/png', 'text/plain'])
496 496 nt.assert_equal(md, {
497 497 'image/png': {
498 498 'width': 5,
499 499 'height': 10,
500 500 }
501 501 })
502 502
503 503
General Comments 0
You need to be logged in to leave comments. Login now