##// END OF EJS Templates
Renamed __pretty__ to _repr_pretty_ and changed updated pretty.py...
Brian Granger -
Show More
@@ -1,576 +1,576 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, Str, CStr
32 32
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # The main DisplayFormatter class
36 36 #-----------------------------------------------------------------------------
37 37
38 38
39 39 class DisplayFormatter(Configurable):
40 40
41 41 # When set to true only the default plain text formatter will be used.
42 42 plain_text_only = Bool(False, config=True)
43 43
44 44 # A dict of formatter whose keys are format types (MIME types) and whose
45 45 # values are subclasses of BaseFormatter.
46 46 formatters = Dict(config=True)
47 47 def _formatters_default(self):
48 48 """Activate the default formatters."""
49 49 formatter_classes = [
50 50 PlainTextFormatter,
51 51 HTMLFormatter,
52 52 SVGFormatter,
53 53 PNGFormatter,
54 54 LatexFormatter,
55 55 JSONFormatter,
56 56 JavascriptFormatter
57 57 ]
58 58 d = {}
59 59 for cls in formatter_classes:
60 60 f = cls(config=self.config)
61 61 d[f.format_type] = f
62 62 return d
63 63
64 64 def format(self, obj, include=None, exclude=None):
65 65 """Return a format data dict for an object.
66 66
67 67 By default all format types will be computed.
68 68
69 69 The following MIME types are currently implemented:
70 70
71 71 * text/plain
72 72 * text/html
73 73 * text/latex
74 74 * application/json
75 75 * image/png
76 76 * immage/svg+xml
77 77
78 78 Parameters
79 79 ----------
80 80 obj : object
81 81 The Python object whose format data will be computed.
82 82 include : list or tuple, optional
83 83 A list of format type strings (MIME types) to include in the
84 84 format data dict. If this is set *only* the format types included
85 85 in this list will be computed.
86 86 exclude : list or tuple, optional
87 87 A list of format type string (MIME types) to exclue in the format
88 88 data dict. If this is set all format types will be computed,
89 89 except for those included in this argument.
90 90
91 91 Returns
92 92 -------
93 93 format_dict : dict
94 94 A dictionary of key/value pairs, one or each format that was
95 95 generated for the object. The keys are the format types, which
96 96 will usually be MIME type strings and the values and JSON'able
97 97 data structure containing the raw data for the representation in
98 98 that format.
99 99 """
100 100 format_dict = {}
101 101
102 102 # If plain text only is active
103 103 if self.plain_text_only:
104 104 formatter = self.formatters['text/plain']
105 105 try:
106 106 data = formatter(obj)
107 107 except:
108 108 # FIXME: log the exception
109 109 raise
110 110 if data is not None:
111 111 format_dict['text/plain'] = data
112 112 return format_dict
113 113
114 114 for format_type, formatter in self.formatters.items():
115 115 if include is not None:
116 116 if format_type not in include:
117 117 continue
118 118 if exclude is not None:
119 119 if format_type in exclude:
120 120 continue
121 121 try:
122 122 data = formatter(obj)
123 123 except:
124 124 # FIXME: log the exception
125 125 raise
126 126 if data is not None:
127 127 format_dict[format_type] = data
128 128 return format_dict
129 129
130 130 @property
131 131 def format_types(self):
132 132 """Return the format types (MIME types) of the active formatters."""
133 133 return self.formatters.keys()
134 134
135 135
136 136 #-----------------------------------------------------------------------------
137 137 # Formatters for specific format types (text, html, svg, etc.)
138 138 #-----------------------------------------------------------------------------
139 139
140 140
141 141 class FormatterABC(object):
142 142 """ Abstract base class for Formatters.
143 143
144 144 A formatter is a callable class that is responsible for computing the
145 145 raw format data for a particular format type (MIME type). For example,
146 146 an HTML formatter would have a format type of `text/html` and would return
147 147 the HTML representation of the object when called.
148 148 """
149 149 __metaclass__ = abc.ABCMeta
150 150
151 151 # The format type of the data returned, usually a MIME type.
152 152 format_type = 'text/plain'
153 153
154 154 # Is the formatter enabled...
155 155 enabled = True
156 156
157 157 @abc.abstractmethod
158 158 def __call__(self, obj):
159 159 """Return a JSON'able representation of the object.
160 160
161 161 If the object cannot be formatted by this formatter, then return None
162 162 """
163 163 try:
164 164 return repr(obj)
165 165 except TypeError:
166 166 return None
167 167
168 168
169 169 class BaseFormatter(Configurable):
170 170 """A base formatter class that is configurable.
171 171
172 172 This formatter should usually be used as the base class of all formatters.
173 173 It is a traited :class:`Configurable` class and includes an extensible
174 174 API for users to determine how their objects are formatted. The following
175 175 logic is used to find a function to format an given object.
176 176
177 177 1. The object is introspected to see if it has a method with the name
178 178 :attr:`print_method`. If is does, that object is passed to that method
179 179 for formatting.
180 180 2. If no print method is found, three internal dictionaries are consulted
181 181 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
182 182 and :attr:`deferred_printers`.
183 183
184 184 Users should use these dictionaries to register functions that will be
185 185 used to compute the format data for their objects (if those objects don't
186 186 have the special print methods). The easiest way of using these
187 187 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
188 188 methods.
189 189
190 190 If no function/callable is found to compute the format data, ``None`` is
191 191 returned and this format type is not used.
192 192 """
193 193
194 194 format_type = Str('text/plain')
195 195
196 196 enabled = Bool(True, config=True)
197 197
198 198 print_method = Str('__repr__')
199 199
200 200 # The singleton printers.
201 201 # Maps the IDs of the builtin singleton objects to the format functions.
202 202 singleton_printers = Dict(config=True)
203 203 def _singleton_printers_default(self):
204 204 return {}
205 205
206 206 # The type-specific printers.
207 207 # Map type objects to the format functions.
208 208 type_printers = Dict(config=True)
209 209 def _type_printers_default(self):
210 210 return {}
211 211
212 212 # The deferred-import type-specific printers.
213 213 # Map (modulename, classname) pairs to the format functions.
214 214 deferred_printers = Dict(config=True)
215 215 def _deferred_printers_default(self):
216 216 return {}
217 217
218 218 def __call__(self, obj):
219 219 """Compute the format for an object."""
220 220 if self.enabled:
221 221 obj_id = id(obj)
222 222 try:
223 223 obj_class = getattr(obj, '__class__', None) or type(obj)
224 224 # First try to find registered singleton printers for the type.
225 225 try:
226 226 printer = self.singleton_printers[obj_id]
227 227 except (TypeError, KeyError):
228 228 pass
229 229 else:
230 230 return printer(obj)
231 231 # Next look for type_printers.
232 232 for cls in pretty._get_mro(obj_class):
233 233 if cls in self.type_printers:
234 234 return self.type_printers[cls](obj)
235 235 else:
236 236 printer = self._in_deferred_types(cls)
237 237 if printer is not None:
238 238 return printer(obj)
239 239 # Finally look for special method names.
240 240 if hasattr(obj_class, self.print_method):
241 241 printer = getattr(obj_class, self.print_method)
242 242 return printer(obj)
243 243 return None
244 244 except Exception:
245 245 pass
246 246 else:
247 247 return None
248 248
249 249 def for_type(self, typ, func):
250 250 """Add a format function for a given type.
251 251
252 252 Parameters
253 253 -----------
254 254 typ : class
255 255 The class of the object that will be formatted using `func`.
256 256 func : callable
257 257 The callable that will be called to compute the format data. The
258 258 call signature of this function is simple, it must take the
259 259 object to be formatted and return the raw data for the given
260 260 format. Subclasses may use a different call signature for the
261 261 `func` argument.
262 262 """
263 263 oldfunc = self.type_printers.get(typ, None)
264 264 if func is not None:
265 265 # To support easy restoration of old printers, we need to ignore
266 266 # Nones.
267 267 self.type_printers[typ] = func
268 268 return oldfunc
269 269
270 270 def for_type_by_name(self, type_module, type_name, func):
271 271 """Add a format function for a type specified by the full dotted
272 272 module and name of the type, rather than the type of the object.
273 273
274 274 Parameters
275 275 ----------
276 276 type_module : str
277 277 The full dotted name of the module the type is defined in, like
278 278 ``numpy``.
279 279 type_name : str
280 280 The name of the type (the class name), like ``dtype``
281 281 func : callable
282 282 The callable that will be called to compute the format data. The
283 283 call signature of this function is simple, it must take the
284 284 object to be formatted and return the raw data for the given
285 285 format. Subclasses may use a different call signature for the
286 286 `func` argument.
287 287 """
288 288 key = (type_module, type_name)
289 289 oldfunc = self.deferred_printers.get(key, None)
290 290 if func is not None:
291 291 # To support easy restoration of old printers, we need to ignore
292 292 # Nones.
293 293 self.deferred_printers[key] = func
294 294 return oldfunc
295 295
296 296 def _in_deferred_types(self, cls):
297 297 """
298 298 Check if the given class is specified in the deferred type registry.
299 299
300 300 Returns the printer from the registry if it exists, and None if the
301 301 class is not in the registry. Successful matches will be moved to the
302 302 regular type registry for future use.
303 303 """
304 304 mod = getattr(cls, '__module__', None)
305 305 name = getattr(cls, '__name__', None)
306 306 key = (mod, name)
307 307 printer = None
308 308 if key in self.deferred_printers:
309 309 # Move the printer over to the regular registry.
310 310 printer = self.deferred_printers.pop(key)
311 311 self.type_printers[cls] = printer
312 312 return printer
313 313
314 314
315 315 class PlainTextFormatter(BaseFormatter):
316 316 """The default pretty-printer.
317 317
318 318 This uses :mod:`IPython.external.pretty` to compute the format data of
319 319 the object. If the object cannot be pretty printed, :func:`repr` is used.
320 320 See the documentation of :mod:`IPython.external.pretty` for details on
321 321 how to write pretty printers. Here is a simple example::
322 322
323 323 def dtype_pprinter(obj, p, cycle):
324 324 if cycle:
325 325 return p.text('dtype(...)')
326 326 if hasattr(obj, 'fields'):
327 327 if obj.fields is None:
328 328 p.text(repr(obj))
329 329 else:
330 330 p.begin_group(7, 'dtype([')
331 331 for i, field in enumerate(obj.descr):
332 332 if i > 0:
333 333 p.text(',')
334 334 p.breakable()
335 335 p.pretty(field)
336 336 p.end_group(7, '])')
337 337 """
338 338
339 339 # The format type of data returned.
340 340 format_type = Str('text/plain')
341 341
342 342 # This subclass ignores this attribute as it always need to return
343 343 # something.
344 344 enabled = Bool(True, config=False)
345 345
346 # Look for a __pretty__ methods to use for pretty printing.
347 print_method = Str('__pretty__')
346 # Look for a _repr_pretty_ methods to use for pretty printing.
347 print_method = Str('_repr_pretty_')
348 348
349 349 # Whether to pretty-print or not.
350 350 pprint = Bool(True, config=True)
351 351
352 352 # Whether to be verbose or not.
353 353 verbose = Bool(False, config=True)
354 354
355 355 # The maximum width.
356 356 max_width = Int(79, config=True)
357 357
358 358 # The newline character.
359 359 newline = Str('\n', config=True)
360 360
361 361 # format-string for pprinting floats
362 362 float_format = Str('%r')
363 363 # setter for float precision, either int or direct format-string
364 364 float_precision = CStr('', config=True)
365 365
366 366 def _float_precision_changed(self, name, old, new):
367 367 """float_precision changed, set float_format accordingly.
368 368
369 369 float_precision can be set by int or str.
370 370 This will set float_format, after interpreting input.
371 371 If numpy has been imported, numpy print precision will also be set.
372 372
373 373 integer `n` sets format to '%.nf', otherwise, format set directly.
374 374
375 375 An empty string returns to defaults (repr for float, 8 for numpy).
376 376
377 377 This parameter can be set via the '%precision' magic.
378 378 """
379 379
380 380 if '%' in new:
381 381 # got explicit format string
382 382 fmt = new
383 383 try:
384 384 fmt%3.14159
385 385 except Exception:
386 386 raise ValueError("Precision must be int or format string, not %r"%new)
387 387 elif new:
388 388 # otherwise, should be an int
389 389 try:
390 390 i = int(new)
391 391 assert i >= 0
392 392 except ValueError:
393 393 raise ValueError("Precision must be int or format string, not %r"%new)
394 394 except AssertionError:
395 395 raise ValueError("int precision must be non-negative, not %r"%i)
396 396
397 397 fmt = '%%.%if'%i
398 398 if 'numpy' in sys.modules:
399 399 # set numpy precision if it has been imported
400 400 import numpy
401 401 numpy.set_printoptions(precision=i)
402 402 else:
403 403 # default back to repr
404 404 fmt = '%r'
405 405 if 'numpy' in sys.modules:
406 406 import numpy
407 407 # numpy default is 8
408 408 numpy.set_printoptions(precision=8)
409 409 self.float_format = fmt
410 410
411 411 # Use the default pretty printers from IPython.external.pretty.
412 412 def _singleton_printers_default(self):
413 413 return pretty._singleton_pprinters.copy()
414 414
415 415 def _type_printers_default(self):
416 416 d = pretty._type_pprinters.copy()
417 417 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
418 418 return d
419 419
420 420 def _deferred_printers_default(self):
421 421 return pretty._deferred_type_pprinters.copy()
422 422
423 423 #### FormatterABC interface ####
424 424
425 425 def __call__(self, obj):
426 426 """Compute the pretty representation of the object."""
427 427 if not self.pprint:
428 428 try:
429 429 return repr(obj)
430 430 except TypeError:
431 431 return ''
432 432 else:
433 433 # This uses use StringIO, as cStringIO doesn't handle unicode.
434 434 stream = StringIO()
435 435 printer = pretty.RepresentationPrinter(stream, self.verbose,
436 436 self.max_width, self.newline,
437 437 singleton_pprinters=self.singleton_printers,
438 438 type_pprinters=self.type_printers,
439 439 deferred_pprinters=self.deferred_printers)
440 440 printer.pretty(obj)
441 441 printer.flush()
442 442 return stream.getvalue()
443 443
444 444
445 445 class HTMLFormatter(BaseFormatter):
446 446 """An HTML formatter.
447 447
448 448 To define the callables that compute the HTML representation of your
449 449 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
450 450 or :meth:`for_type_by_name` methods to register functions that handle
451 451 this.
452 452 """
453 453 format_type = Str('text/html')
454 454
455 455 print_method = Str('_repr_html_')
456 456
457 457
458 458 class SVGFormatter(BaseFormatter):
459 459 """An SVG formatter.
460 460
461 461 To define the callables that compute the SVG representation of your
462 462 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
463 463 or :meth:`for_type_by_name` methods to register functions that handle
464 464 this.
465 465 """
466 466 format_type = Str('image/svg+xml')
467 467
468 468 print_method = Str('_repr_svg_')
469 469
470 470
471 471 class PNGFormatter(BaseFormatter):
472 472 """A PNG formatter.
473 473
474 474 To define the callables that compute the PNG representation of your
475 475 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
476 476 or :meth:`for_type_by_name` methods to register functions that handle
477 477 this.
478 478
479 479 The raw data should be the base64 encoded raw png data.
480 480 """
481 481 format_type = Str('image/png')
482 482
483 483 print_method = Str('_repr_png_')
484 484
485 485
486 486 class LatexFormatter(BaseFormatter):
487 487 """A LaTeX formatter.
488 488
489 489 To define the callables that compute the LaTeX representation of your
490 490 objects, define a :meth:`_repr_latex_` 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 format_type = Str('text/latex')
495 495
496 496 print_method = Str('_repr_latex_')
497 497
498 498
499 499 class JSONFormatter(BaseFormatter):
500 500 """A JSON string formatter.
501 501
502 502 To define the callables that compute the JSON string representation of
503 503 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
504 504 or :meth:`for_type_by_name` methods to register functions that handle
505 505 this.
506 506 """
507 507 format_type = Str('application/json')
508 508
509 509 print_method = Str('_repr_json_')
510 510
511 511
512 512 class JavascriptFormatter(BaseFormatter):
513 513 """A Javascript formatter.
514 514
515 515 To define the callables that compute the Javascript representation of
516 516 your objects, define a :meth:`_repr_javascript_` method or use the
517 517 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
518 518 that handle this.
519 519 """
520 520 format_type = Str('application/javascript')
521 521
522 522 print_method = Str('_repr_javascript_')
523 523
524 524 FormatterABC.register(BaseFormatter)
525 525 FormatterABC.register(PlainTextFormatter)
526 526 FormatterABC.register(HTMLFormatter)
527 527 FormatterABC.register(SVGFormatter)
528 528 FormatterABC.register(PNGFormatter)
529 529 FormatterABC.register(LatexFormatter)
530 530 FormatterABC.register(JSONFormatter)
531 531 FormatterABC.register(JavascriptFormatter)
532 532
533 533
534 534 def format_display_data(obj, include=None, exclude=None):
535 535 """Return a format data dict for an object.
536 536
537 537 By default all format types will be computed.
538 538
539 539 The following MIME types are currently implemented:
540 540
541 541 * text/plain
542 542 * text/html
543 543 * text/latex
544 544 * application/json
545 545 * image/png
546 546 * immage/svg+xml
547 547
548 548 Parameters
549 549 ----------
550 550 obj : object
551 551 The Python object whose format data will be computed.
552 552
553 553 Returns
554 554 -------
555 555 format_dict : dict
556 556 A dictionary of key/value pairs, one or each format that was
557 557 generated for the object. The keys are the format types, which
558 558 will usually be MIME type strings and the values and JSON'able
559 559 data structure containing the raw data for the representation in
560 560 that format.
561 561 include : list or tuple, optional
562 562 A list of format type strings (MIME types) to include in the
563 563 format data dict. If this is set *only* the format types included
564 564 in this list will be computed.
565 565 exclude : list or tuple, optional
566 566 A list of format type string (MIME types) to exclue in the format
567 567 data dict. If this is set all format types will be computed,
568 568 except for those included in this argument.
569 569 """
570 570 from IPython.core.interactiveshell import InteractiveShell
571 571
572 572 InteractiveShell.instance().display_formatter.format(
573 573 obj,
574 574 include,
575 575 exclude
576 576 )
@@ -1,700 +1,703 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 pretty
4 4 ~~
5 5
6 6 Python advanced pretty printer. This pretty printer is intended to
7 7 replace the old `pprint` python module which does not allow developers
8 8 to provide their own pretty print callbacks.
9 9
10 10 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
11 11
12 12
13 13 Example Usage
14 14 =============
15 15
16 16 To directly print the representation of an object use `pprint`::
17 17
18 18 from pretty import pprint
19 19 pprint(complex_object)
20 20
21 21 To get a string of the output use `pretty`::
22 22
23 23 from pretty import pretty
24 24 string = pretty(complex_object)
25 25
26 26
27 27 Extending
28 28 =========
29 29
30 30 The pretty library allows developers to add pretty printing rules for their
31 31 own objects. This process is straightforward. All you have to do is to
32 add a `__pretty__` method to your object and call the methods on the
32 add a `_repr_pretty_` method to your object and call the methods on the
33 33 pretty printer passed::
34 34
35 35 class MyObject(object):
36 36
37 def __pretty__(self, p, cycle):
37 def _repr_pretty_(self, p, cycle):
38 38 ...
39 39
40 40 Depending on the python version you want to support you have two
41 41 possibilities. The following list shows the python 2.5 version and the
42 42 compatibility one.
43 43
44 44
45 Here the example implementation of a `__pretty__` method for a list
45 Here the example implementation of a `_repr_pretty_` method for a list
46 46 subclass for python 2.5 and higher (python 2.5 requires the with statement
47 47 __future__ import)::
48 48
49 49 class MyList(list):
50 50
51 def __pretty__(self, p, cycle):
51 def _repr_pretty_(self, p, cycle):
52 52 if cycle:
53 53 p.text('MyList(...)')
54 54 else:
55 55 with p.group(8, 'MyList([', '])'):
56 56 for idx, item in enumerate(self):
57 57 if idx:
58 58 p.text(',')
59 59 p.breakable()
60 60 p.pretty(item)
61 61
62 62 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
63 63 react to that or the result is an infinite loop. `p.text()` just adds
64 64 non breaking text to the output, `p.breakable()` either adds a whitespace
65 65 or breaks here. If you pass it an argument it's used instead of the
66 66 default space. `p.pretty` prettyprints another object using the pretty print
67 67 method.
68 68
69 69 The first parameter to the `group` function specifies the extra indentation
70 70 of the next line. In this example the next item will either be not
71 71 breaked (if the items are short enough) or aligned with the right edge of
72 72 the opening bracked of `MyList`.
73 73
74 74 If you want to support python 2.4 and lower you can use this code::
75 75
76 76 class MyList(list):
77 77
78 def __pretty__(self, p, cycle):
78 def _repr_pretty_(self, p, cycle):
79 79 if cycle:
80 80 p.text('MyList(...)')
81 81 else:
82 82 p.begin_group(8, 'MyList([')
83 83 for idx, item in enumerate(self):
84 84 if idx:
85 85 p.text(',')
86 86 p.breakable()
87 87 p.pretty(item)
88 88 p.end_group(8, '])')
89 89
90 90 If you just want to indent something you can use the group function
91 91 without open / close parameters. Under python 2.5 you can also use this
92 92 code::
93 93
94 94 with p.indent(2):
95 95 ...
96 96
97 97 Or under python2.4 you might want to modify ``p.indentation`` by hand but
98 98 this is rather ugly.
99 99
100 100 :copyright: 2007 by Armin Ronacher.
101 101 Portions (c) 2009 by Robert Kern.
102 102 :license: BSD License.
103 103 """
104 104 from __future__ import with_statement
105 105 from contextlib import contextmanager
106 106 import sys
107 107 import types
108 108 import re
109 109 import datetime
110 110 from StringIO import StringIO
111 111 from collections import deque
112 112
113 113
114 114 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
115 115 'for_type', 'for_type_by_name']
116 116
117 117
118 118 _re_pattern_type = type(re.compile(''))
119 119
120 120
121 121 def pretty(obj, verbose=False, max_width=79, newline='\n'):
122 122 """
123 123 Pretty print the object's representation.
124 124 """
125 125 stream = StringIO()
126 126 printer = RepresentationPrinter(stream, verbose, max_width, newline)
127 127 printer.pretty(obj)
128 128 printer.flush()
129 129 return stream.getvalue()
130 130
131 131
132 132 def pprint(obj, verbose=False, max_width=79, newline='\n'):
133 133 """
134 134 Like `pretty` but print to stdout.
135 135 """
136 136 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)
137 137 printer.pretty(obj)
138 138 printer.flush()
139 139 sys.stdout.write(newline)
140 140 sys.stdout.flush()
141 141
142 142 class _PrettyPrinterBase(object):
143 143
144 144 @contextmanager
145 145 def indent(self, indent):
146 146 """with statement support for indenting/dedenting."""
147 147 self.indentation += indent
148 148 try:
149 149 yield
150 150 finally:
151 151 self.indentation -= indent
152 152
153 153 @contextmanager
154 154 def group(self, indent=0, open='', close=''):
155 155 """like begin_group / end_group but for the with statement."""
156 156 self.begin_group(indent, open)
157 157 try:
158 158 with self.indent(indent):
159 159 yield
160 160 finally:
161 161 self.end_group(indent, close)
162 162
163 163 class PrettyPrinter(_PrettyPrinterBase):
164 164 """
165 165 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
166 166 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
167 this printer knows nothing about the default pprinters or the `__pretty__`
167 this printer knows nothing about the default pprinters or the `_repr_pretty_`
168 168 callback method.
169 169 """
170 170
171 171 def __init__(self, output, max_width=79, newline='\n'):
172 172 self.output = output
173 173 self.max_width = max_width
174 174 self.newline = newline
175 175 self.output_width = 0
176 176 self.buffer_width = 0
177 177 self.buffer = deque()
178 178
179 179 root_group = Group(0)
180 180 self.group_stack = [root_group]
181 181 self.group_queue = GroupQueue(root_group)
182 182 self.indentation = 0
183 183
184 184 def _break_outer_groups(self):
185 185 while self.max_width < self.output_width + self.buffer_width:
186 186 group = self.group_queue.deq()
187 187 if not group:
188 188 return
189 189 while group.breakables:
190 190 x = self.buffer.popleft()
191 191 self.output_width = x.output(self.output, self.output_width)
192 192 self.buffer_width -= x.width
193 193 while self.buffer and isinstance(self.buffer[0], Text):
194 194 x = self.buffer.popleft()
195 195 self.output_width = x.output(self.output, self.output_width)
196 196 self.buffer_width -= x.width
197 197
198 198 def text(self, obj):
199 199 """Add literal text to the output."""
200 200 width = len(obj)
201 201 if self.buffer:
202 202 text = self.buffer[-1]
203 203 if not isinstance(text, Text):
204 204 text = Text()
205 205 self.buffer.append(text)
206 206 text.add(obj, width)
207 207 self.buffer_width += width
208 208 self._break_outer_groups()
209 209 else:
210 210 self.output.write(obj)
211 211 self.output_width += width
212 212
213 213 def breakable(self, sep=' '):
214 214 """
215 215 Add a breakable separator to the output. This does not mean that it
216 216 will automatically break here. If no breaking on this position takes
217 217 place the `sep` is inserted which default to one space.
218 218 """
219 219 width = len(sep)
220 220 group = self.group_stack[-1]
221 221 if group.want_break:
222 222 self.flush()
223 223 self.output.write(self.newline)
224 224 self.output.write(' ' * self.indentation)
225 225 self.output_width = self.indentation
226 226 self.buffer_width = 0
227 227 else:
228 228 self.buffer.append(Breakable(sep, width, self))
229 229 self.buffer_width += width
230 230 self._break_outer_groups()
231 231
232 232
233 233 def begin_group(self, indent=0, open=''):
234 234 """
235 235 Begin a group. If you want support for python < 2.5 which doesn't has
236 236 the with statement this is the preferred way:
237 237
238 238 p.begin_group(1, '{')
239 239 ...
240 240 p.end_group(1, '}')
241 241
242 242 The python 2.5 expression would be this:
243 243
244 244 with p.group(1, '{', '}'):
245 245 ...
246 246
247 247 The first parameter specifies the indentation for the next line (usually
248 248 the width of the opening text), the second the opening text. All
249 249 parameters are optional.
250 250 """
251 251 if open:
252 252 self.text(open)
253 253 group = Group(self.group_stack[-1].depth + 1)
254 254 self.group_stack.append(group)
255 255 self.group_queue.enq(group)
256 256 self.indentation += indent
257 257
258 258 def end_group(self, dedent=0, close=''):
259 259 """End a group. See `begin_group` for more details."""
260 260 self.indentation -= dedent
261 261 group = self.group_stack.pop()
262 262 if not group.breakables:
263 263 self.group_queue.remove(group)
264 264 if close:
265 265 self.text(close)
266 266
267 267 def flush(self):
268 268 """Flush data that is left in the buffer."""
269 269 for data in self.buffer:
270 270 self.output_width += data.output(self.output, self.output_width)
271 271 self.buffer.clear()
272 272 self.buffer_width = 0
273 273
274 274
275 275 def _get_mro(obj_class):
276 276 """ Get a reasonable method resolution order of a class and its superclasses
277 277 for both old-style and new-style classes.
278 278 """
279 279 if not hasattr(obj_class, '__mro__'):
280 280 # Old-style class. Mix in object to make a fake new-style class.
281 281 try:
282 282 obj_class = type(obj_class.__name__, (obj_class, object), {})
283 283 except TypeError:
284 284 # Old-style extension type that does not descend from object.
285 285 # FIXME: try to construct a more thorough MRO.
286 286 mro = [obj_class]
287 287 else:
288 288 mro = obj_class.__mro__[1:-1]
289 289 else:
290 290 mro = obj_class.__mro__
291 291 return mro
292 292
293 293
294 294 class RepresentationPrinter(PrettyPrinter):
295 295 """
296 296 Special pretty printer that has a `pretty` method that calls the pretty
297 297 printer for a python object.
298 298
299 299 This class stores processing data on `self` so you must *never* use
300 300 this class in a threaded environment. Always lock it or reinstanciate
301 301 it.
302 302
303 303 Instances also have a verbose flag callbacks can access to control their
304 304 output. For example the default instance repr prints all attributes and
305 305 methods that are not prefixed by an underscore if the printer is in
306 306 verbose mode.
307 307 """
308 308
309 309 def __init__(self, output, verbose=False, max_width=79, newline='\n',
310 310 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None):
311 311
312 312 PrettyPrinter.__init__(self, output, max_width, newline)
313 313 self.verbose = verbose
314 314 self.stack = []
315 315 if singleton_pprinters is None:
316 316 singleton_pprinters = _singleton_pprinters.copy()
317 317 self.singleton_pprinters = singleton_pprinters
318 318 if type_pprinters is None:
319 319 type_pprinters = _type_pprinters.copy()
320 320 self.type_pprinters = type_pprinters
321 321 if deferred_pprinters is None:
322 322 deferred_pprinters = _deferred_type_pprinters.copy()
323 323 self.deferred_pprinters = deferred_pprinters
324 324
325 325 def pretty(self, obj):
326 326 """Pretty print the given object."""
327 327 obj_id = id(obj)
328 328 cycle = obj_id in self.stack
329 329 self.stack.append(obj_id)
330 330 self.begin_group()
331 331 try:
332 332 obj_class = getattr(obj, '__class__', None) or type(obj)
333 if hasattr(obj_class, '__pretty__'):
334 return obj_class.__pretty__(obj, self, cycle)
333 # First try to find registered singleton printers for the type.
335 334 try:
336 335 printer = self.singleton_pprinters[obj_id]
337 336 except (TypeError, KeyError):
338 337 pass
339 338 else:
340 339 return printer(obj, self, cycle)
340 # Next look for type_printers.
341 341 for cls in _get_mro(obj_class):
342 342 if cls in self.type_pprinters:
343 343 return self.type_pprinters[cls](obj, self, cycle)
344 344 else:
345 345 printer = self._in_deferred_types(cls)
346 346 if printer is not None:
347 347 return printer(obj, self, cycle)
348 # Finally look for special method names.
349 if hasattr(obj_class, '_repr_pretty_'):
350 return obj_class._repr_pretty_(obj, self, cycle)
348 351 return _default_pprint(obj, self, cycle)
349 352 finally:
350 353 self.end_group()
351 354 self.stack.pop()
352 355
353 356 def _in_deferred_types(self, cls):
354 357 """
355 358 Check if the given class is specified in the deferred type registry.
356 359
357 360 Returns the printer from the registry if it exists, and None if the
358 361 class is not in the registry. Successful matches will be moved to the
359 362 regular type registry for future use.
360 363 """
361 364 mod = getattr(cls, '__module__', None)
362 365 name = getattr(cls, '__name__', None)
363 366 key = (mod, name)
364 367 printer = None
365 368 if key in self.deferred_pprinters:
366 369 # Move the printer over to the regular registry.
367 370 printer = self.deferred_pprinters.pop(key)
368 371 self.type_pprinters[cls] = printer
369 372 return printer
370 373
371 374
372 375 class Printable(object):
373 376
374 377 def output(self, stream, output_width):
375 378 return output_width
376 379
377 380
378 381 class Text(Printable):
379 382
380 383 def __init__(self):
381 384 self.objs = []
382 385 self.width = 0
383 386
384 387 def output(self, stream, output_width):
385 388 for obj in self.objs:
386 389 stream.write(obj)
387 390 return output_width + self.width
388 391
389 392 def add(self, obj, width):
390 393 self.objs.append(obj)
391 394 self.width += width
392 395
393 396
394 397 class Breakable(Printable):
395 398
396 399 def __init__(self, seq, width, pretty):
397 400 self.obj = seq
398 401 self.width = width
399 402 self.pretty = pretty
400 403 self.indentation = pretty.indentation
401 404 self.group = pretty.group_stack[-1]
402 405 self.group.breakables.append(self)
403 406
404 407 def output(self, stream, output_width):
405 408 self.group.breakables.popleft()
406 409 if self.group.want_break:
407 410 stream.write(self.pretty.newline)
408 411 stream.write(' ' * self.indentation)
409 412 return self.indentation
410 413 if not self.group.breakables:
411 414 self.pretty.group_queue.remove(self.group)
412 415 stream.write(self.obj)
413 416 return output_width + self.width
414 417
415 418
416 419 class Group(Printable):
417 420
418 421 def __init__(self, depth):
419 422 self.depth = depth
420 423 self.breakables = deque()
421 424 self.want_break = False
422 425
423 426
424 427 class GroupQueue(object):
425 428
426 429 def __init__(self, *groups):
427 430 self.queue = []
428 431 for group in groups:
429 432 self.enq(group)
430 433
431 434 def enq(self, group):
432 435 depth = group.depth
433 436 while depth > len(self.queue) - 1:
434 437 self.queue.append([])
435 438 self.queue[depth].append(group)
436 439
437 440 def deq(self):
438 441 for stack in self.queue:
439 442 for idx, group in enumerate(reversed(stack)):
440 443 if group.breakables:
441 444 del stack[idx]
442 445 group.want_break = True
443 446 return group
444 447 for group in stack:
445 448 group.want_break = True
446 449 del stack[:]
447 450
448 451 def remove(self, group):
449 452 try:
450 453 self.queue[group.depth].remove(group)
451 454 except ValueError:
452 455 pass
453 456
454 457
455 458 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
456 459
457 460
458 461 def _default_pprint(obj, p, cycle):
459 462 """
460 463 The default print function. Used if an object does not provide one and
461 464 it's none of the builtin objects.
462 465 """
463 466 klass = getattr(obj, '__class__', None) or type(obj)
464 467 if getattr(klass, '__repr__', None) not in _baseclass_reprs:
465 468 # A user-provided repr.
466 469 p.text(repr(obj))
467 470 return
468 471 p.begin_group(1, '<')
469 472 p.pretty(klass)
470 473 p.text(' at 0x%x' % id(obj))
471 474 if cycle:
472 475 p.text(' ...')
473 476 elif p.verbose:
474 477 first = True
475 478 for key in dir(obj):
476 479 if not key.startswith('_'):
477 480 try:
478 481 value = getattr(obj, key)
479 482 except AttributeError:
480 483 continue
481 484 if isinstance(value, types.MethodType):
482 485 continue
483 486 if not first:
484 487 p.text(',')
485 488 p.breakable()
486 489 p.text(key)
487 490 p.text('=')
488 491 step = len(key) + 1
489 492 p.indentation += step
490 493 p.pretty(value)
491 494 p.indentation -= step
492 495 first = False
493 496 p.end_group(1, '>')
494 497
495 498
496 499 def _seq_pprinter_factory(start, end):
497 500 """
498 501 Factory that returns a pprint function useful for sequences. Used by
499 502 the default pprint for tuples, dicts, lists, sets and frozensets.
500 503 """
501 504 def inner(obj, p, cycle):
502 505 if cycle:
503 506 return p.text(start + '...' + end)
504 507 step = len(start)
505 508 p.begin_group(step, start)
506 509 for idx, x in enumerate(obj):
507 510 if idx:
508 511 p.text(',')
509 512 p.breakable()
510 513 p.pretty(x)
511 514 if len(obj) == 1 and type(obj) is tuple:
512 515 # Special case for 1-item tuples.
513 516 p.text(',')
514 517 p.end_group(step, end)
515 518 return inner
516 519
517 520
518 521 def _dict_pprinter_factory(start, end):
519 522 """
520 523 Factory that returns a pprint function used by the default pprint of
521 524 dicts and dict proxies.
522 525 """
523 526 def inner(obj, p, cycle):
524 527 if cycle:
525 528 return p.text('{...}')
526 529 p.begin_group(1, start)
527 530 keys = obj.keys()
528 531 try:
529 532 keys.sort()
530 533 except Exception, e:
531 534 # Sometimes the keys don't sort.
532 535 pass
533 536 for idx, key in enumerate(keys):
534 537 if idx:
535 538 p.text(',')
536 539 p.breakable()
537 540 p.pretty(key)
538 541 p.text(': ')
539 542 p.pretty(obj[key])
540 543 p.end_group(1, end)
541 544 return inner
542 545
543 546
544 547 def _super_pprint(obj, p, cycle):
545 548 """The pprint for the super type."""
546 549 p.begin_group(8, '<super: ')
547 550 p.pretty(obj.__self_class__)
548 551 p.text(',')
549 552 p.breakable()
550 553 p.pretty(obj.__self__)
551 554 p.end_group(8, '>')
552 555
553 556
554 557 def _re_pattern_pprint(obj, p, cycle):
555 558 """The pprint function for regular expression patterns."""
556 559 p.text('re.compile(')
557 560 pattern = repr(obj.pattern)
558 561 if pattern[:1] in 'uU':
559 562 pattern = pattern[1:]
560 563 prefix = 'ur'
561 564 else:
562 565 prefix = 'r'
563 566 pattern = prefix + pattern.replace('\\\\', '\\')
564 567 p.text(pattern)
565 568 if obj.flags:
566 569 p.text(',')
567 570 p.breakable()
568 571 done_one = False
569 572 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
570 573 'UNICODE', 'VERBOSE', 'DEBUG'):
571 574 if obj.flags & getattr(re, flag):
572 575 if done_one:
573 576 p.text('|')
574 577 p.text('re.' + flag)
575 578 done_one = True
576 579 p.text(')')
577 580
578 581
579 582 def _type_pprint(obj, p, cycle):
580 583 """The pprint for classes and types."""
581 584 if obj.__module__ in ('__builtin__', 'exceptions'):
582 585 name = obj.__name__
583 586 else:
584 587 name = obj.__module__ + '.' + obj.__name__
585 588 p.text(name)
586 589
587 590
588 591 def _repr_pprint(obj, p, cycle):
589 592 """A pprint that just redirects to the normal repr function."""
590 593 p.text(repr(obj))
591 594
592 595
593 596 def _function_pprint(obj, p, cycle):
594 597 """Base pprint for all functions and builtin functions."""
595 598 if obj.__module__ in ('__builtin__', 'exceptions') or not obj.__module__:
596 599 name = obj.__name__
597 600 else:
598 601 name = obj.__module__ + '.' + obj.__name__
599 602 p.text('<function %s>' % name)
600 603
601 604
602 605 def _exception_pprint(obj, p, cycle):
603 606 """Base pprint for all exceptions."""
604 607 if obj.__class__.__module__ == 'exceptions':
605 608 name = obj.__class__.__name__
606 609 else:
607 610 name = '%s.%s' % (
608 611 obj.__class__.__module__,
609 612 obj.__class__.__name__
610 613 )
611 614 step = len(name) + 1
612 615 p.begin_group(step, '(')
613 616 for idx, arg in enumerate(getattr(obj, 'args', ())):
614 617 if idx:
615 618 p.text(',')
616 619 p.breakable()
617 620 p.pretty(arg)
618 621 p.end_group(step, ')')
619 622
620 623
621 624 #: the exception base
622 625 try:
623 626 _exception_base = BaseException
624 627 except NameError:
625 628 _exception_base = Exception
626 629
627 630
628 631 #: printers for builtin types
629 632 _type_pprinters = {
630 633 int: _repr_pprint,
631 634 long: _repr_pprint,
632 635 float: _repr_pprint,
633 636 str: _repr_pprint,
634 637 unicode: _repr_pprint,
635 638 tuple: _seq_pprinter_factory('(', ')'),
636 639 list: _seq_pprinter_factory('[', ']'),
637 640 dict: _dict_pprinter_factory('{', '}'),
638 641 types.DictProxyType: _dict_pprinter_factory('<dictproxy {', '}>'),
639 642 set: _seq_pprinter_factory('set([', '])'),
640 643 frozenset: _seq_pprinter_factory('frozenset([', '])'),
641 644 super: _super_pprint,
642 645 _re_pattern_type: _re_pattern_pprint,
643 646 type: _type_pprint,
644 647 types.ClassType: _type_pprint,
645 648 types.FunctionType: _function_pprint,
646 649 types.BuiltinFunctionType: _function_pprint,
647 650 types.SliceType: _repr_pprint,
648 651 types.MethodType: _repr_pprint,
649 652 xrange: _repr_pprint,
650 653 datetime.datetime: _repr_pprint,
651 654 datetime.timedelta: _repr_pprint,
652 655 _exception_base: _exception_pprint
653 656 }
654 657
655 658 #: printers for types specified by name
656 659 _deferred_type_pprinters = {
657 660 }
658 661
659 662 def for_type(typ, func):
660 663 """
661 664 Add a pretty printer for a given type.
662 665 """
663 666 oldfunc = _type_pprinters.get(typ, None)
664 667 if func is not None:
665 668 # To support easy restoration of old pprinters, we need to ignore Nones.
666 669 _type_pprinters[typ] = func
667 670 return oldfunc
668 671
669 672 def for_type_by_name(type_module, type_name, func):
670 673 """
671 674 Add a pretty printer for a type specified by the module and name of a type
672 675 rather than the type object itself.
673 676 """
674 677 key = (type_module, type_name)
675 678 oldfunc = _deferred_type_pprinters.get(key, None)
676 679 if func is not None:
677 680 # To support easy restoration of old pprinters, we need to ignore Nones.
678 681 _deferred_type_pprinters[key] = func
679 682 return oldfunc
680 683
681 684
682 685 #: printers for the default singletons
683 686 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
684 687 NotImplemented]), _repr_pprint)
685 688
686 689
687 690 if __name__ == '__main__':
688 691 from random import randrange
689 692 class Foo(object):
690 693 def __init__(self):
691 694 self.foo = 1
692 695 self.bar = re.compile(r'\s+')
693 696 self.blub = dict.fromkeys(range(30), randrange(1, 40))
694 697 self.hehe = 23424.234234
695 698 self.list = ["blub", "blah", self]
696 699
697 700 def get_foo(self):
698 701 print "foo"
699 702
700 703 pprint(Foo(), verbose=True)
@@ -1,26 +1,24 b''
1 1 """Code that shows off the IPython display logic.
2 2 """
3 3
4 4 from IPython.core.display import (
5 5 display, display_pretty, display_html,
6 6 display_svg, display_json
7 7 )
8 8
9 9 class Circle(object):
10 10
11 11 def __init__(self, radius):
12 12 self.radius = radius
13 13
14 14 def _repr_pretty_(self, p, cycle):
15 15 p.text(u"\u25CB")
16 16
17 __pretty__ = _repr_pretty_
18
19 17 def _repr_html_(self):
20 18 return "<h1>Cirle: radius=%s</h1>" % self.radius
21 19
22 20 def _repr_svg_(self):
23 21 return """<svg>
24 22 <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
25 23 </svg>"""
26 24
General Comments 0
You need to be logged in to leave comments. Login now