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