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