##// END OF EJS Templates
tweak formatter.for_type...
MinRK -
Show More
@@ -1,654 +1,681 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4 Inheritance diagram:
5 5
6 6 .. inheritance-diagram:: IPython.core.formatters
7 7 :parts: 3
8 8
9 9 Authors:
10 10
11 11 * Robert Kern
12 12 * Brian Granger
13 13 """
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2010-2011, IPython Development Team.
16 16 #
17 17 # Distributed under the terms of the Modified BSD License.
18 18 #
19 19 # The full license is in the file COPYING.txt, distributed with this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 # Stdlib imports
27 27 import abc
28 28 import sys
29 29 import warnings
30 30
31 31 # Our own imports
32 32 from IPython.config.configurable import Configurable
33 33 from IPython.lib import pretty
34 34 from IPython.utils.traitlets import (
35 35 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
36 36 )
37 37 from IPython.utils.py3compat import unicode_to_str, with_metaclass, PY3
38 38
39 39 if PY3:
40 40 from io import StringIO
41 41 else:
42 42 from StringIO import StringIO
43 43
44 44
45 45 #-----------------------------------------------------------------------------
46 46 # The main DisplayFormatter class
47 47 #-----------------------------------------------------------------------------
48 48
49 _current = object()
49 50
50 51 class DisplayFormatter(Configurable):
51 52
52 53 # When set to true only the default plain text formatter will be used.
53 54 plain_text_only = Bool(False, config=True)
54 55 def _plain_text_only_changed(self, name, old, new):
55 56 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
56 57
57 58 Use DisplayFormatter.active_types = ['text/plain']
58 59 for the same effect.
59 60 """, DeprecationWarning)
60 61 if new:
61 62 self.active_types = ['text/plain']
62 63 else:
63 64 self.active_types = self.format_types
64 65
65 66 active_types = List(Unicode, config=True,
66 67 help="""List of currently active mime-types to display.
67 68 You can use this to set a white-list for formats to display.
68 69
69 70 Most users will not need to change this value.
70 71 """)
71 72 def _active_types_default(self):
72 73 return self.format_types
73 74
74 75 def _active_types_changed(self, name, old, new):
75 76 for key, formatter in self.formatters.items():
76 77 if key in new:
77 78 formatter.enabled = True
78 79 else:
79 80 formatter.enabled = False
80 81
81 82 # A dict of formatter whose keys are format types (MIME types) and whose
82 83 # values are subclasses of BaseFormatter.
83 84 formatters = Dict()
84 85 def _formatters_default(self):
85 86 """Activate the default formatters."""
86 87 formatter_classes = [
87 88 PlainTextFormatter,
88 89 HTMLFormatter,
89 90 SVGFormatter,
90 91 PNGFormatter,
91 92 JPEGFormatter,
92 93 LatexFormatter,
93 94 JSONFormatter,
94 95 JavascriptFormatter
95 96 ]
96 97 d = {}
97 98 for cls in formatter_classes:
98 99 f = cls(parent=self)
99 100 d[f.format_type] = f
100 101 return d
101 102
102 103 def format(self, obj, include=None, exclude=None):
103 104 """Return a format data dict for an object.
104 105
105 106 By default all format types will be computed.
106 107
107 108 The following MIME types are currently implemented:
108 109
109 110 * text/plain
110 111 * text/html
111 112 * text/latex
112 113 * application/json
113 114 * application/javascript
114 115 * image/png
115 116 * image/jpeg
116 117 * image/svg+xml
117 118
118 119 Parameters
119 120 ----------
120 121 obj : object
121 122 The Python object whose format data will be computed.
122 123 include : list or tuple, optional
123 124 A list of format type strings (MIME types) to include in the
124 125 format data dict. If this is set *only* the format types included
125 126 in this list will be computed.
126 127 exclude : list or tuple, optional
127 128 A list of format type string (MIME types) to exclude in the format
128 129 data dict. If this is set all format types will be computed,
129 130 except for those included in this argument.
130 131
131 132 Returns
132 133 -------
133 134 (format_dict, metadata_dict) : tuple of two dicts
134 135
135 136 format_dict is a dictionary of key/value pairs, one of each format that was
136 137 generated for the object. The keys are the format types, which
137 138 will usually be MIME type strings and the values and JSON'able
138 139 data structure containing the raw data for the representation in
139 140 that format.
140 141
141 142 metadata_dict is a dictionary of metadata about each mime-type output.
142 143 Its keys will be a strict subset of the keys in format_dict.
143 144 """
144 145 format_dict = {}
145 146 md_dict = {}
146 147
147 148 for format_type, formatter in self.formatters.items():
148 149 if include and format_type not in include:
149 150 continue
150 151 if exclude and format_type in exclude:
151 152 continue
152 153
153 154 md = None
154 155 try:
155 156 data = formatter(obj)
156 157 except:
157 158 # FIXME: log the exception
158 159 raise
159 160
160 161 # formatters can return raw data or (data, metadata)
161 162 if isinstance(data, tuple) and len(data) == 2:
162 163 data, md = data
163 164
164 165 if data is not None:
165 166 format_dict[format_type] = data
166 167 if md is not None:
167 168 md_dict[format_type] = md
168 169
169 170 return format_dict, md_dict
170 171
171 172 @property
172 173 def format_types(self):
173 174 """Return the format types (MIME types) of the active formatters."""
174 175 return list(self.formatters.keys())
175 176
176 177
177 178 #-----------------------------------------------------------------------------
178 179 # Formatters for specific format types (text, html, svg, etc.)
179 180 #-----------------------------------------------------------------------------
180 181
181 182
182 183 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
183 184 """ Abstract base class for Formatters.
184 185
185 186 A formatter is a callable class that is responsible for computing the
186 187 raw format data for a particular format type (MIME type). For example,
187 188 an HTML formatter would have a format type of `text/html` and would return
188 189 the HTML representation of the object when called.
189 190 """
190 191
191 192 # The format type of the data returned, usually a MIME type.
192 193 format_type = 'text/plain'
193 194
194 195 # Is the formatter enabled...
195 196 enabled = True
196 197
197 198 @abc.abstractmethod
198 199 def __call__(self, obj):
199 200 """Return a JSON'able representation of the object.
200 201
201 202 If the object cannot be formatted by this formatter, then return None
202 203 """
203 204 try:
204 205 return repr(obj)
205 206 except Exception:
206 207 return None
207 208
208 209
209 210 class BaseFormatter(Configurable):
210 211 """A base formatter class that is configurable.
211 212
212 213 This formatter should usually be used as the base class of all formatters.
213 214 It is a traited :class:`Configurable` class and includes an extensible
214 215 API for users to determine how their objects are formatted. The following
215 216 logic is used to find a function to format an given object.
216 217
217 218 1. The object is introspected to see if it has a method with the name
218 219 :attr:`print_method`. If is does, that object is passed to that method
219 220 for formatting.
220 221 2. If no print method is found, three internal dictionaries are consulted
221 222 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
222 223 and :attr:`deferred_printers`.
223 224
224 225 Users should use these dictionaries to register functions that will be
225 226 used to compute the format data for their objects (if those objects don't
226 227 have the special print methods). The easiest way of using these
227 228 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
228 229 methods.
229 230
230 231 If no function/callable is found to compute the format data, ``None`` is
231 232 returned and this format type is not used.
232 233 """
233 234
234 235 format_type = Unicode('text/plain')
235 236
236 237 enabled = Bool(True, config=True)
237 238
238 239 print_method = ObjectName('__repr__')
239 240
240 241 # The singleton printers.
241 242 # Maps the IDs of the builtin singleton objects to the format functions.
242 243 singleton_printers = Dict(config=True)
243 244 def _singleton_printers_default(self):
244 245 return {}
245 246
246 247 # The type-specific printers.
247 248 # Map type objects to the format functions.
248 249 type_printers = Dict(config=True)
249 250 def _type_printers_default(self):
250 251 return {}
251 252
252 253 # The deferred-import type-specific printers.
253 254 # Map (modulename, classname) pairs to the format functions.
254 255 deferred_printers = Dict(config=True)
255 256 def _deferred_printers_default(self):
256 257 return {}
257 258
258 259 def __call__(self, obj):
259 260 """Compute the format for an object."""
260 261 if self.enabled:
261 262 obj_id = id(obj)
262 263 try:
263 264 obj_class = getattr(obj, '__class__', None) or type(obj)
264 265 # First try to find registered singleton printers for the type.
265 266 try:
266 267 printer = self.singleton_printers[obj_id]
267 268 except (TypeError, KeyError):
268 269 pass
269 270 else:
270 271 return printer(obj)
271 272 # Next look for type_printers.
272 273 for cls in pretty._get_mro(obj_class):
273 274 if cls in self.type_printers:
274 275 return self.type_printers[cls](obj)
275 276 else:
276 277 printer = self._in_deferred_types(cls)
277 278 if printer is not None:
278 279 return printer(obj)
279 280 # Finally look for special method names.
280 281 if hasattr(obj_class, self.print_method):
281 282 printer = getattr(obj_class, self.print_method)
282 283 return printer(obj)
283 284 return None
284 285 except Exception:
285 286 pass
286 287 else:
287 288 return None
288 289
289 def for_type(self, typ, func):
290 def for_type(self, typ, func=_current):
290 291 """Add a format function for a given type.
291
292
292 293 Parameters
293 294 -----------
294 295 typ : class
295 296 The class of the object that will be formatted using `func`.
296 297 func : callable
297 The callable that will be called to compute the format data. The
298 call signature of this function is simple, it must take the
299 object to be formatted and return the raw data for the given
300 format. Subclasses may use a different call signature for the
298 A callable for computing the format data.
299 `func` will be called with the object to be formatted,
300 and will return the raw data in this formatter's format.
301 Subclasses may use a different call signature for the
301 302 `func` argument.
303
304 If None is given, the current formatter for the type, if any,
305 will be cleared.
306
307 If `func` is not specified, there will be no change,
308 only returning the current value.
309
310 Returns
311 -------
312 oldfunc : callable
313 The currently registered callable.
314 If you are registering a new formatter,
315 this will be the previous value (to enable restoring later).
302 316 """
303 317 oldfunc = self.type_printers.get(typ, None)
304 if func is not None:
305 # To support easy restoration of old printers, we need to ignore
306 # Nones.
318 if func is None:
319 self.type_printers.pop(typ, None)
320 elif func is not _current:
307 321 self.type_printers[typ] = func
308 322 return oldfunc
309 323
310 def for_type_by_name(self, type_module, type_name, func):
324 def for_type_by_name(self, type_module, type_name, func=_current):
311 325 """Add a format function for a type specified by the full dotted
312 326 module and name of the type, rather than the type of the object.
313 327
314 328 Parameters
315 329 ----------
316 330 type_module : str
317 331 The full dotted name of the module the type is defined in, like
318 332 ``numpy``.
319 333 type_name : str
320 334 The name of the type (the class name), like ``dtype``
321 335 func : callable
322 The callable that will be called to compute the format data. The
323 call signature of this function is simple, it must take the
324 object to be formatted and return the raw data for the given
325 format. Subclasses may use a different call signature for the
336 A callable for computing the format data.
337 `func` will be called with the object to be formatted,
338 and will return the raw data in this formatter's format.
339 Subclasses may use a different call signature for the
326 340 `func` argument.
341
342 If None is given, the current formatter for the type, if any,
343 will be cleared.
344
345 If `func` is not specified, there will be no change,
346 only returning the current value.
347
348 Returns
349 -------
350 oldfunc : callable
351 The currently registered callable.
352 If you are registering a new formatter,
353 this will be the previous value (to enable restoring later).
327 354 """
328 355 key = (type_module, type_name)
329 356 oldfunc = self.deferred_printers.get(key, None)
330 if func is not None:
331 # To support easy restoration of old printers, we need to ignore
332 # Nones.
357 if func is None:
358 self.deferred_printers.pop(key, None)
359 elif func is not _current:
333 360 self.deferred_printers[key] = func
334 361 return oldfunc
335 362
336 363 def _in_deferred_types(self, cls):
337 364 """
338 365 Check if the given class is specified in the deferred type registry.
339 366
340 367 Returns the printer from the registry if it exists, and None if the
341 368 class is not in the registry. Successful matches will be moved to the
342 369 regular type registry for future use.
343 370 """
344 371 mod = getattr(cls, '__module__', None)
345 372 name = getattr(cls, '__name__', None)
346 373 key = (mod, name)
347 374 printer = None
348 375 if key in self.deferred_printers:
349 376 # Move the printer over to the regular registry.
350 377 printer = self.deferred_printers.pop(key)
351 378 self.type_printers[cls] = printer
352 379 return printer
353 380
354 381
355 382 class PlainTextFormatter(BaseFormatter):
356 383 """The default pretty-printer.
357 384
358 385 This uses :mod:`IPython.lib.pretty` to compute the format data of
359 386 the object. If the object cannot be pretty printed, :func:`repr` is used.
360 387 See the documentation of :mod:`IPython.lib.pretty` for details on
361 388 how to write pretty printers. Here is a simple example::
362 389
363 390 def dtype_pprinter(obj, p, cycle):
364 391 if cycle:
365 392 return p.text('dtype(...)')
366 393 if hasattr(obj, 'fields'):
367 394 if obj.fields is None:
368 395 p.text(repr(obj))
369 396 else:
370 397 p.begin_group(7, 'dtype([')
371 398 for i, field in enumerate(obj.descr):
372 399 if i > 0:
373 400 p.text(',')
374 401 p.breakable()
375 402 p.pretty(field)
376 403 p.end_group(7, '])')
377 404 """
378 405
379 406 # The format type of data returned.
380 407 format_type = Unicode('text/plain')
381 408
382 409 # This subclass ignores this attribute as it always need to return
383 410 # something.
384 411 enabled = Bool(True, config=False)
385 412
386 413 # Look for a _repr_pretty_ methods to use for pretty printing.
387 414 print_method = ObjectName('_repr_pretty_')
388 415
389 416 # Whether to pretty-print or not.
390 417 pprint = Bool(True, config=True)
391 418
392 419 # Whether to be verbose or not.
393 420 verbose = Bool(False, config=True)
394 421
395 422 # The maximum width.
396 423 max_width = Integer(79, config=True)
397 424
398 425 # The newline character.
399 426 newline = Unicode('\n', config=True)
400 427
401 428 # format-string for pprinting floats
402 429 float_format = Unicode('%r')
403 430 # setter for float precision, either int or direct format-string
404 431 float_precision = CUnicode('', config=True)
405 432
406 433 def _float_precision_changed(self, name, old, new):
407 434 """float_precision changed, set float_format accordingly.
408 435
409 436 float_precision can be set by int or str.
410 437 This will set float_format, after interpreting input.
411 438 If numpy has been imported, numpy print precision will also be set.
412 439
413 440 integer `n` sets format to '%.nf', otherwise, format set directly.
414 441
415 442 An empty string returns to defaults (repr for float, 8 for numpy).
416 443
417 444 This parameter can be set via the '%precision' magic.
418 445 """
419 446
420 447 if '%' in new:
421 448 # got explicit format string
422 449 fmt = new
423 450 try:
424 451 fmt%3.14159
425 452 except Exception:
426 453 raise ValueError("Precision must be int or format string, not %r"%new)
427 454 elif new:
428 455 # otherwise, should be an int
429 456 try:
430 457 i = int(new)
431 458 assert i >= 0
432 459 except ValueError:
433 460 raise ValueError("Precision must be int or format string, not %r"%new)
434 461 except AssertionError:
435 462 raise ValueError("int precision must be non-negative, not %r"%i)
436 463
437 464 fmt = '%%.%if'%i
438 465 if 'numpy' in sys.modules:
439 466 # set numpy precision if it has been imported
440 467 import numpy
441 468 numpy.set_printoptions(precision=i)
442 469 else:
443 470 # default back to repr
444 471 fmt = '%r'
445 472 if 'numpy' in sys.modules:
446 473 import numpy
447 474 # numpy default is 8
448 475 numpy.set_printoptions(precision=8)
449 476 self.float_format = fmt
450 477
451 478 # Use the default pretty printers from IPython.lib.pretty.
452 479 def _singleton_printers_default(self):
453 480 return pretty._singleton_pprinters.copy()
454 481
455 482 def _type_printers_default(self):
456 483 d = pretty._type_pprinters.copy()
457 484 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
458 485 return d
459 486
460 487 def _deferred_printers_default(self):
461 488 return pretty._deferred_type_pprinters.copy()
462 489
463 490 #### FormatterABC interface ####
464 491
465 492 def __call__(self, obj):
466 493 """Compute the pretty representation of the object."""
467 494 if not self.pprint:
468 495 return pretty._safe_repr(obj)
469 496 else:
470 497 # This uses use StringIO, as cStringIO doesn't handle unicode.
471 498 stream = StringIO()
472 499 # self.newline.encode() is a quick fix for issue gh-597. We need to
473 500 # ensure that stream does not get a mix of unicode and bytestrings,
474 501 # or it will cause trouble.
475 502 printer = pretty.RepresentationPrinter(stream, self.verbose,
476 503 self.max_width, unicode_to_str(self.newline),
477 504 singleton_pprinters=self.singleton_printers,
478 505 type_pprinters=self.type_printers,
479 506 deferred_pprinters=self.deferred_printers)
480 507 printer.pretty(obj)
481 508 printer.flush()
482 509 return stream.getvalue()
483 510
484 511
485 512 class HTMLFormatter(BaseFormatter):
486 513 """An HTML formatter.
487 514
488 515 To define the callables that compute the HTML representation of your
489 516 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
490 517 or :meth:`for_type_by_name` methods to register functions that handle
491 518 this.
492 519
493 520 The return value of this formatter should be a valid HTML snippet that
494 521 could be injected into an existing DOM. It should *not* include the
495 522 ```<html>`` or ```<body>`` tags.
496 523 """
497 524 format_type = Unicode('text/html')
498 525
499 526 print_method = ObjectName('_repr_html_')
500 527
501 528
502 529 class SVGFormatter(BaseFormatter):
503 530 """An SVG formatter.
504 531
505 532 To define the callables that compute the SVG representation of your
506 533 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
507 534 or :meth:`for_type_by_name` methods to register functions that handle
508 535 this.
509 536
510 537 The return value of this formatter should be valid SVG enclosed in
511 538 ```<svg>``` tags, that could be injected into an existing DOM. It should
512 539 *not* include the ```<html>`` or ```<body>`` tags.
513 540 """
514 541 format_type = Unicode('image/svg+xml')
515 542
516 543 print_method = ObjectName('_repr_svg_')
517 544
518 545
519 546 class PNGFormatter(BaseFormatter):
520 547 """A PNG formatter.
521 548
522 549 To define the callables that compute the PNG representation of your
523 550 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
524 551 or :meth:`for_type_by_name` methods to register functions that handle
525 552 this.
526 553
527 554 The return value of this formatter should be raw PNG data, *not*
528 555 base64 encoded.
529 556 """
530 557 format_type = Unicode('image/png')
531 558
532 559 print_method = ObjectName('_repr_png_')
533 560
534 561
535 562 class JPEGFormatter(BaseFormatter):
536 563 """A JPEG formatter.
537 564
538 565 To define the callables that compute the JPEG representation of your
539 566 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
540 567 or :meth:`for_type_by_name` methods to register functions that handle
541 568 this.
542 569
543 570 The return value of this formatter should be raw JPEG data, *not*
544 571 base64 encoded.
545 572 """
546 573 format_type = Unicode('image/jpeg')
547 574
548 575 print_method = ObjectName('_repr_jpeg_')
549 576
550 577
551 578 class LatexFormatter(BaseFormatter):
552 579 """A LaTeX formatter.
553 580
554 581 To define the callables that compute the LaTeX representation of your
555 582 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
556 583 or :meth:`for_type_by_name` methods to register functions that handle
557 584 this.
558 585
559 586 The return value of this formatter should be a valid LaTeX equation,
560 587 enclosed in either ```$```, ```$$``` or another LaTeX equation
561 588 environment.
562 589 """
563 590 format_type = Unicode('text/latex')
564 591
565 592 print_method = ObjectName('_repr_latex_')
566 593
567 594
568 595 class JSONFormatter(BaseFormatter):
569 596 """A JSON string formatter.
570 597
571 598 To define the callables that compute the JSON string representation of
572 599 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
573 600 or :meth:`for_type_by_name` methods to register functions that handle
574 601 this.
575 602
576 603 The return value of this formatter should be a valid JSON string.
577 604 """
578 605 format_type = Unicode('application/json')
579 606
580 607 print_method = ObjectName('_repr_json_')
581 608
582 609
583 610 class JavascriptFormatter(BaseFormatter):
584 611 """A Javascript formatter.
585 612
586 613 To define the callables that compute the Javascript representation of
587 614 your objects, define a :meth:`_repr_javascript_` method or use the
588 615 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
589 616 that handle this.
590 617
591 618 The return value of this formatter should be valid Javascript code and
592 619 should *not* be enclosed in ```<script>``` tags.
593 620 """
594 621 format_type = Unicode('application/javascript')
595 622
596 623 print_method = ObjectName('_repr_javascript_')
597 624
598 625 FormatterABC.register(BaseFormatter)
599 626 FormatterABC.register(PlainTextFormatter)
600 627 FormatterABC.register(HTMLFormatter)
601 628 FormatterABC.register(SVGFormatter)
602 629 FormatterABC.register(PNGFormatter)
603 630 FormatterABC.register(JPEGFormatter)
604 631 FormatterABC.register(LatexFormatter)
605 632 FormatterABC.register(JSONFormatter)
606 633 FormatterABC.register(JavascriptFormatter)
607 634
608 635
609 636 def format_display_data(obj, include=None, exclude=None):
610 637 """Return a format data dict for an object.
611 638
612 639 By default all format types will be computed.
613 640
614 641 The following MIME types are currently implemented:
615 642
616 643 * text/plain
617 644 * text/html
618 645 * text/latex
619 646 * application/json
620 647 * application/javascript
621 648 * image/png
622 649 * image/jpeg
623 650 * image/svg+xml
624 651
625 652 Parameters
626 653 ----------
627 654 obj : object
628 655 The Python object whose format data will be computed.
629 656
630 657 Returns
631 658 -------
632 659 format_dict : dict
633 660 A dictionary of key/value pairs, one or each format that was
634 661 generated for the object. The keys are the format types, which
635 662 will usually be MIME type strings and the values and JSON'able
636 663 data structure containing the raw data for the representation in
637 664 that format.
638 665 include : list or tuple, optional
639 666 A list of format type strings (MIME types) to include in the
640 667 format data dict. If this is set *only* the format types included
641 668 in this list will be computed.
642 669 exclude : list or tuple, optional
643 670 A list of format type string (MIME types) to exclue in the format
644 671 data dict. If this is set all format types will be computed,
645 672 except for those included in this argument.
646 673 """
647 674 from IPython.core.interactiveshell import InteractiveShell
648 675
649 676 InteractiveShell.instance().display_formatter.format(
650 677 obj,
651 678 include,
652 679 exclude
653 680 )
654 681
General Comments 0
You need to be logged in to leave comments. Login now