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