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