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