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