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