##// END OF EJS Templates
Merge pull request #4459 from minrk/bad-repr...
Thomas Kluyver -
r13489:49af4ae9 merge
parent child Browse files
Show More
@@ -1,657 +1,654 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
31 31 # Our own imports
32 32 from IPython.config.configurable import Configurable
33 33 from IPython.lib import pretty
34 34 from IPython.utils.traitlets import (
35 35 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
36 36 )
37 37 from IPython.utils.py3compat import unicode_to_str, with_metaclass, PY3
38 38
39 39 if PY3:
40 40 from io import StringIO
41 41 else:
42 42 from StringIO import StringIO
43 43
44 44
45 45 #-----------------------------------------------------------------------------
46 46 # The main DisplayFormatter class
47 47 #-----------------------------------------------------------------------------
48 48
49 49
50 50 class DisplayFormatter(Configurable):
51 51
52 52 # When set to true only the default plain text formatter will be used.
53 53 plain_text_only = Bool(False, config=True)
54 54 def _plain_text_only_changed(self, name, old, new):
55 55 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
56 56
57 57 Use DisplayFormatter.active_types = ['text/plain']
58 58 for the same effect.
59 59 """, DeprecationWarning)
60 60 if new:
61 61 self.active_types = ['text/plain']
62 62 else:
63 63 self.active_types = self.format_types
64 64
65 65 active_types = List(Unicode, config=True,
66 66 help="""List of currently active mime-types to display.
67 67 You can use this to set a white-list for formats to display.
68 68
69 69 Most users will not need to change this value.
70 70 """)
71 71 def _active_types_default(self):
72 72 return self.format_types
73 73
74 74 def _active_types_changed(self, name, old, new):
75 75 for key, formatter in self.formatters.items():
76 76 if key in new:
77 77 formatter.enabled = True
78 78 else:
79 79 formatter.enabled = False
80 80
81 81 # A dict of formatter whose keys are format types (MIME types) and whose
82 82 # values are subclasses of BaseFormatter.
83 83 formatters = Dict()
84 84 def _formatters_default(self):
85 85 """Activate the default formatters."""
86 86 formatter_classes = [
87 87 PlainTextFormatter,
88 88 HTMLFormatter,
89 89 SVGFormatter,
90 90 PNGFormatter,
91 91 JPEGFormatter,
92 92 LatexFormatter,
93 93 JSONFormatter,
94 94 JavascriptFormatter
95 95 ]
96 96 d = {}
97 97 for cls in formatter_classes:
98 98 f = cls(parent=self)
99 99 d[f.format_type] = f
100 100 return d
101 101
102 102 def format(self, obj, include=None, exclude=None):
103 103 """Return a format data dict for an object.
104 104
105 105 By default all format types will be computed.
106 106
107 107 The following MIME types are currently implemented:
108 108
109 109 * text/plain
110 110 * text/html
111 111 * text/latex
112 112 * application/json
113 113 * application/javascript
114 114 * image/png
115 115 * image/jpeg
116 116 * image/svg+xml
117 117
118 118 Parameters
119 119 ----------
120 120 obj : object
121 121 The Python object whose format data will be computed.
122 122 include : list or tuple, optional
123 123 A list of format type strings (MIME types) to include in the
124 124 format data dict. If this is set *only* the format types included
125 125 in this list will be computed.
126 126 exclude : list or tuple, optional
127 127 A list of format type string (MIME types) to exclude in the format
128 128 data dict. If this is set all format types will be computed,
129 129 except for those included in this argument.
130 130
131 131 Returns
132 132 -------
133 133 (format_dict, metadata_dict) : tuple of two dicts
134 134
135 135 format_dict is a dictionary of key/value pairs, one of each format that was
136 136 generated for the object. The keys are the format types, which
137 137 will usually be MIME type strings and the values and JSON'able
138 138 data structure containing the raw data for the representation in
139 139 that format.
140 140
141 141 metadata_dict is a dictionary of metadata about each mime-type output.
142 142 Its keys will be a strict subset of the keys in format_dict.
143 143 """
144 144 format_dict = {}
145 145 md_dict = {}
146 146
147 147 for format_type, formatter in self.formatters.items():
148 148 if include and format_type not in include:
149 149 continue
150 150 if exclude and format_type in exclude:
151 151 continue
152 152
153 153 md = None
154 154 try:
155 155 data = formatter(obj)
156 156 except:
157 157 # FIXME: log the exception
158 158 raise
159 159
160 160 # formatters can return raw data or (data, metadata)
161 161 if isinstance(data, tuple) and len(data) == 2:
162 162 data, md = data
163 163
164 164 if data is not None:
165 165 format_dict[format_type] = data
166 166 if md is not None:
167 167 md_dict[format_type] = md
168 168
169 169 return format_dict, md_dict
170 170
171 171 @property
172 172 def format_types(self):
173 173 """Return the format types (MIME types) of the active formatters."""
174 174 return list(self.formatters.keys())
175 175
176 176
177 177 #-----------------------------------------------------------------------------
178 178 # Formatters for specific format types (text, html, svg, etc.)
179 179 #-----------------------------------------------------------------------------
180 180
181 181
182 182 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
183 183 """ Abstract base class for Formatters.
184 184
185 185 A formatter is a callable class that is responsible for computing the
186 186 raw format data for a particular format type (MIME type). For example,
187 187 an HTML formatter would have a format type of `text/html` and would return
188 188 the HTML representation of the object when called.
189 189 """
190 190
191 191 # The format type of the data returned, usually a MIME type.
192 192 format_type = 'text/plain'
193 193
194 194 # Is the formatter enabled...
195 195 enabled = True
196 196
197 197 @abc.abstractmethod
198 198 def __call__(self, obj):
199 199 """Return a JSON'able representation of the object.
200 200
201 201 If the object cannot be formatted by this formatter, then return None
202 202 """
203 203 try:
204 204 return repr(obj)
205 except TypeError:
205 except Exception:
206 206 return None
207 207
208 208
209 209 class BaseFormatter(Configurable):
210 210 """A base formatter class that is configurable.
211 211
212 212 This formatter should usually be used as the base class of all formatters.
213 213 It is a traited :class:`Configurable` class and includes an extensible
214 214 API for users to determine how their objects are formatted. The following
215 215 logic is used to find a function to format an given object.
216 216
217 217 1. The object is introspected to see if it has a method with the name
218 218 :attr:`print_method`. If is does, that object is passed to that method
219 219 for formatting.
220 220 2. If no print method is found, three internal dictionaries are consulted
221 221 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
222 222 and :attr:`deferred_printers`.
223 223
224 224 Users should use these dictionaries to register functions that will be
225 225 used to compute the format data for their objects (if those objects don't
226 226 have the special print methods). The easiest way of using these
227 227 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
228 228 methods.
229 229
230 230 If no function/callable is found to compute the format data, ``None`` is
231 231 returned and this format type is not used.
232 232 """
233 233
234 234 format_type = Unicode('text/plain')
235 235
236 236 enabled = Bool(True, config=True)
237 237
238 238 print_method = ObjectName('__repr__')
239 239
240 240 # The singleton printers.
241 241 # Maps the IDs of the builtin singleton objects to the format functions.
242 242 singleton_printers = Dict(config=True)
243 243 def _singleton_printers_default(self):
244 244 return {}
245 245
246 246 # The type-specific printers.
247 247 # Map type objects to the format functions.
248 248 type_printers = Dict(config=True)
249 249 def _type_printers_default(self):
250 250 return {}
251 251
252 252 # The deferred-import type-specific printers.
253 253 # Map (modulename, classname) pairs to the format functions.
254 254 deferred_printers = Dict(config=True)
255 255 def _deferred_printers_default(self):
256 256 return {}
257 257
258 258 def __call__(self, obj):
259 259 """Compute the format for an object."""
260 260 if self.enabled:
261 261 obj_id = id(obj)
262 262 try:
263 263 obj_class = getattr(obj, '__class__', None) or type(obj)
264 264 # First try to find registered singleton printers for the type.
265 265 try:
266 266 printer = self.singleton_printers[obj_id]
267 267 except (TypeError, KeyError):
268 268 pass
269 269 else:
270 270 return printer(obj)
271 271 # Next look for type_printers.
272 272 for cls in pretty._get_mro(obj_class):
273 273 if cls in self.type_printers:
274 274 return self.type_printers[cls](obj)
275 275 else:
276 276 printer = self._in_deferred_types(cls)
277 277 if printer is not None:
278 278 return printer(obj)
279 279 # Finally look for special method names.
280 280 if hasattr(obj_class, self.print_method):
281 281 printer = getattr(obj_class, self.print_method)
282 282 return printer(obj)
283 283 return None
284 284 except Exception:
285 285 pass
286 286 else:
287 287 return None
288 288
289 289 def for_type(self, typ, func):
290 290 """Add a format function for a given type.
291 291
292 292 Parameters
293 293 -----------
294 294 typ : class
295 295 The class of the object that will be formatted using `func`.
296 296 func : callable
297 297 The callable that will be called to compute the format data. The
298 298 call signature of this function is simple, it must take the
299 299 object to be formatted and return the raw data for the given
300 300 format. Subclasses may use a different call signature for the
301 301 `func` argument.
302 302 """
303 303 oldfunc = self.type_printers.get(typ, None)
304 304 if func is not None:
305 305 # To support easy restoration of old printers, we need to ignore
306 306 # Nones.
307 307 self.type_printers[typ] = func
308 308 return oldfunc
309 309
310 310 def for_type_by_name(self, type_module, type_name, func):
311 311 """Add a format function for a type specified by the full dotted
312 312 module and name of the type, rather than the type of the object.
313 313
314 314 Parameters
315 315 ----------
316 316 type_module : str
317 317 The full dotted name of the module the type is defined in, like
318 318 ``numpy``.
319 319 type_name : str
320 320 The name of the type (the class name), like ``dtype``
321 321 func : callable
322 322 The callable that will be called to compute the format data. The
323 323 call signature of this function is simple, it must take the
324 324 object to be formatted and return the raw data for the given
325 325 format. Subclasses may use a different call signature for the
326 326 `func` argument.
327 327 """
328 328 key = (type_module, type_name)
329 329 oldfunc = self.deferred_printers.get(key, None)
330 330 if func is not None:
331 331 # To support easy restoration of old printers, we need to ignore
332 332 # Nones.
333 333 self.deferred_printers[key] = func
334 334 return oldfunc
335 335
336 336 def _in_deferred_types(self, cls):
337 337 """
338 338 Check if the given class is specified in the deferred type registry.
339 339
340 340 Returns the printer from the registry if it exists, and None if the
341 341 class is not in the registry. Successful matches will be moved to the
342 342 regular type registry for future use.
343 343 """
344 344 mod = getattr(cls, '__module__', None)
345 345 name = getattr(cls, '__name__', None)
346 346 key = (mod, name)
347 347 printer = None
348 348 if key in self.deferred_printers:
349 349 # Move the printer over to the regular registry.
350 350 printer = self.deferred_printers.pop(key)
351 351 self.type_printers[cls] = printer
352 352 return printer
353 353
354 354
355 355 class PlainTextFormatter(BaseFormatter):
356 356 """The default pretty-printer.
357 357
358 358 This uses :mod:`IPython.lib.pretty` to compute the format data of
359 359 the object. If the object cannot be pretty printed, :func:`repr` is used.
360 360 See the documentation of :mod:`IPython.lib.pretty` for details on
361 361 how to write pretty printers. Here is a simple example::
362 362
363 363 def dtype_pprinter(obj, p, cycle):
364 364 if cycle:
365 365 return p.text('dtype(...)')
366 366 if hasattr(obj, 'fields'):
367 367 if obj.fields is None:
368 368 p.text(repr(obj))
369 369 else:
370 370 p.begin_group(7, 'dtype([')
371 371 for i, field in enumerate(obj.descr):
372 372 if i > 0:
373 373 p.text(',')
374 374 p.breakable()
375 375 p.pretty(field)
376 376 p.end_group(7, '])')
377 377 """
378 378
379 379 # The format type of data returned.
380 380 format_type = Unicode('text/plain')
381 381
382 382 # This subclass ignores this attribute as it always need to return
383 383 # something.
384 384 enabled = Bool(True, config=False)
385 385
386 386 # Look for a _repr_pretty_ methods to use for pretty printing.
387 387 print_method = ObjectName('_repr_pretty_')
388 388
389 389 # Whether to pretty-print or not.
390 390 pprint = Bool(True, config=True)
391 391
392 392 # Whether to be verbose or not.
393 393 verbose = Bool(False, config=True)
394 394
395 395 # The maximum width.
396 396 max_width = Integer(79, config=True)
397 397
398 398 # The newline character.
399 399 newline = Unicode('\n', config=True)
400 400
401 401 # format-string for pprinting floats
402 402 float_format = Unicode('%r')
403 403 # setter for float precision, either int or direct format-string
404 404 float_precision = CUnicode('', config=True)
405 405
406 406 def _float_precision_changed(self, name, old, new):
407 407 """float_precision changed, set float_format accordingly.
408 408
409 409 float_precision can be set by int or str.
410 410 This will set float_format, after interpreting input.
411 411 If numpy has been imported, numpy print precision will also be set.
412 412
413 413 integer `n` sets format to '%.nf', otherwise, format set directly.
414 414
415 415 An empty string returns to defaults (repr for float, 8 for numpy).
416 416
417 417 This parameter can be set via the '%precision' magic.
418 418 """
419 419
420 420 if '%' in new:
421 421 # got explicit format string
422 422 fmt = new
423 423 try:
424 424 fmt%3.14159
425 425 except Exception:
426 426 raise ValueError("Precision must be int or format string, not %r"%new)
427 427 elif new:
428 428 # otherwise, should be an int
429 429 try:
430 430 i = int(new)
431 431 assert i >= 0
432 432 except ValueError:
433 433 raise ValueError("Precision must be int or format string, not %r"%new)
434 434 except AssertionError:
435 435 raise ValueError("int precision must be non-negative, not %r"%i)
436 436
437 437 fmt = '%%.%if'%i
438 438 if 'numpy' in sys.modules:
439 439 # set numpy precision if it has been imported
440 440 import numpy
441 441 numpy.set_printoptions(precision=i)
442 442 else:
443 443 # default back to repr
444 444 fmt = '%r'
445 445 if 'numpy' in sys.modules:
446 446 import numpy
447 447 # numpy default is 8
448 448 numpy.set_printoptions(precision=8)
449 449 self.float_format = fmt
450 450
451 451 # Use the default pretty printers from IPython.lib.pretty.
452 452 def _singleton_printers_default(self):
453 453 return pretty._singleton_pprinters.copy()
454 454
455 455 def _type_printers_default(self):
456 456 d = pretty._type_pprinters.copy()
457 457 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
458 458 return d
459 459
460 460 def _deferred_printers_default(self):
461 461 return pretty._deferred_type_pprinters.copy()
462 462
463 463 #### FormatterABC interface ####
464 464
465 465 def __call__(self, obj):
466 466 """Compute the pretty representation of the object."""
467 467 if not self.pprint:
468 try:
469 return repr(obj)
470 except TypeError:
471 return ''
468 return pretty._safe_repr(obj)
472 469 else:
473 470 # This uses use StringIO, as cStringIO doesn't handle unicode.
474 471 stream = StringIO()
475 472 # self.newline.encode() is a quick fix for issue gh-597. We need to
476 473 # ensure that stream does not get a mix of unicode and bytestrings,
477 474 # or it will cause trouble.
478 475 printer = pretty.RepresentationPrinter(stream, self.verbose,
479 476 self.max_width, unicode_to_str(self.newline),
480 477 singleton_pprinters=self.singleton_printers,
481 478 type_pprinters=self.type_printers,
482 479 deferred_pprinters=self.deferred_printers)
483 480 printer.pretty(obj)
484 481 printer.flush()
485 482 return stream.getvalue()
486 483
487 484
488 485 class HTMLFormatter(BaseFormatter):
489 486 """An HTML formatter.
490 487
491 488 To define the callables that compute the HTML representation of your
492 489 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
493 490 or :meth:`for_type_by_name` methods to register functions that handle
494 491 this.
495 492
496 493 The return value of this formatter should be a valid HTML snippet that
497 494 could be injected into an existing DOM. It should *not* include the
498 495 ```<html>`` or ```<body>`` tags.
499 496 """
500 497 format_type = Unicode('text/html')
501 498
502 499 print_method = ObjectName('_repr_html_')
503 500
504 501
505 502 class SVGFormatter(BaseFormatter):
506 503 """An SVG formatter.
507 504
508 505 To define the callables that compute the SVG representation of your
509 506 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
510 507 or :meth:`for_type_by_name` methods to register functions that handle
511 508 this.
512 509
513 510 The return value of this formatter should be valid SVG enclosed in
514 511 ```<svg>``` tags, that could be injected into an existing DOM. It should
515 512 *not* include the ```<html>`` or ```<body>`` tags.
516 513 """
517 514 format_type = Unicode('image/svg+xml')
518 515
519 516 print_method = ObjectName('_repr_svg_')
520 517
521 518
522 519 class PNGFormatter(BaseFormatter):
523 520 """A PNG formatter.
524 521
525 522 To define the callables that compute the PNG representation of your
526 523 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
527 524 or :meth:`for_type_by_name` methods to register functions that handle
528 525 this.
529 526
530 527 The return value of this formatter should be raw PNG data, *not*
531 528 base64 encoded.
532 529 """
533 530 format_type = Unicode('image/png')
534 531
535 532 print_method = ObjectName('_repr_png_')
536 533
537 534
538 535 class JPEGFormatter(BaseFormatter):
539 536 """A JPEG formatter.
540 537
541 538 To define the callables that compute the JPEG representation of your
542 539 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
543 540 or :meth:`for_type_by_name` methods to register functions that handle
544 541 this.
545 542
546 543 The return value of this formatter should be raw JPEG data, *not*
547 544 base64 encoded.
548 545 """
549 546 format_type = Unicode('image/jpeg')
550 547
551 548 print_method = ObjectName('_repr_jpeg_')
552 549
553 550
554 551 class LatexFormatter(BaseFormatter):
555 552 """A LaTeX formatter.
556 553
557 554 To define the callables that compute the LaTeX representation of your
558 555 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
559 556 or :meth:`for_type_by_name` methods to register functions that handle
560 557 this.
561 558
562 559 The return value of this formatter should be a valid LaTeX equation,
563 560 enclosed in either ```$```, ```$$``` or another LaTeX equation
564 561 environment.
565 562 """
566 563 format_type = Unicode('text/latex')
567 564
568 565 print_method = ObjectName('_repr_latex_')
569 566
570 567
571 568 class JSONFormatter(BaseFormatter):
572 569 """A JSON string formatter.
573 570
574 571 To define the callables that compute the JSON string representation of
575 572 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
576 573 or :meth:`for_type_by_name` methods to register functions that handle
577 574 this.
578 575
579 576 The return value of this formatter should be a valid JSON string.
580 577 """
581 578 format_type = Unicode('application/json')
582 579
583 580 print_method = ObjectName('_repr_json_')
584 581
585 582
586 583 class JavascriptFormatter(BaseFormatter):
587 584 """A Javascript formatter.
588 585
589 586 To define the callables that compute the Javascript representation of
590 587 your objects, define a :meth:`_repr_javascript_` method or use the
591 588 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
592 589 that handle this.
593 590
594 591 The return value of this formatter should be valid Javascript code and
595 592 should *not* be enclosed in ```<script>``` tags.
596 593 """
597 594 format_type = Unicode('application/javascript')
598 595
599 596 print_method = ObjectName('_repr_javascript_')
600 597
601 598 FormatterABC.register(BaseFormatter)
602 599 FormatterABC.register(PlainTextFormatter)
603 600 FormatterABC.register(HTMLFormatter)
604 601 FormatterABC.register(SVGFormatter)
605 602 FormatterABC.register(PNGFormatter)
606 603 FormatterABC.register(JPEGFormatter)
607 604 FormatterABC.register(LatexFormatter)
608 605 FormatterABC.register(JSONFormatter)
609 606 FormatterABC.register(JavascriptFormatter)
610 607
611 608
612 609 def format_display_data(obj, include=None, exclude=None):
613 610 """Return a format data dict for an object.
614 611
615 612 By default all format types will be computed.
616 613
617 614 The following MIME types are currently implemented:
618 615
619 616 * text/plain
620 617 * text/html
621 618 * text/latex
622 619 * application/json
623 620 * application/javascript
624 621 * image/png
625 622 * image/jpeg
626 623 * image/svg+xml
627 624
628 625 Parameters
629 626 ----------
630 627 obj : object
631 628 The Python object whose format data will be computed.
632 629
633 630 Returns
634 631 -------
635 632 format_dict : dict
636 633 A dictionary of key/value pairs, one or each format that was
637 634 generated for the object. The keys are the format types, which
638 635 will usually be MIME type strings and the values and JSON'able
639 636 data structure containing the raw data for the representation in
640 637 that format.
641 638 include : list or tuple, optional
642 639 A list of format type strings (MIME types) to include in the
643 640 format data dict. If this is set *only* the format types included
644 641 in this list will be computed.
645 642 exclude : list or tuple, optional
646 643 A list of format type string (MIME types) to exclue in the format
647 644 data dict. If this is set all format types will be computed,
648 645 except for those included in this argument.
649 646 """
650 647 from IPython.core.interactiveshell import InteractiveShell
651 648
652 649 InteractiveShell.instance().display_formatter.format(
653 650 obj,
654 651 include,
655 652 exclude
656 653 )
657 654
@@ -1,797 +1,851 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Python advanced pretty printer. This pretty printer is intended to
4 4 replace the old `pprint` python module which does not allow developers
5 5 to provide their own pretty print callbacks.
6 6
7 7 This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
8 8
9 9
10 10 Example Usage
11 11 -------------
12 12
13 13 To directly print the representation of an object use `pprint`::
14 14
15 15 from pretty import pprint
16 16 pprint(complex_object)
17 17
18 18 To get a string of the output use `pretty`::
19 19
20 20 from pretty import pretty
21 21 string = pretty(complex_object)
22 22
23 23
24 24 Extending
25 25 ---------
26 26
27 27 The pretty library allows developers to add pretty printing rules for their
28 28 own objects. This process is straightforward. All you have to do is to
29 29 add a `_repr_pretty_` method to your object and call the methods on the
30 30 pretty printer passed::
31 31
32 32 class MyObject(object):
33 33
34 34 def _repr_pretty_(self, p, cycle):
35 35 ...
36 36
37 37 Depending on the python version you want to support you have two
38 38 possibilities. The following list shows the python 2.5 version and the
39 39 compatibility one.
40 40
41 41
42 42 Here the example implementation of a `_repr_pretty_` method for a list
43 43 subclass for python 2.5 and higher (python 2.5 requires the with statement
44 44 __future__ import)::
45 45
46 46 class MyList(list):
47 47
48 48 def _repr_pretty_(self, p, cycle):
49 49 if cycle:
50 50 p.text('MyList(...)')
51 51 else:
52 52 with p.group(8, 'MyList([', '])'):
53 53 for idx, item in enumerate(self):
54 54 if idx:
55 55 p.text(',')
56 56 p.breakable()
57 57 p.pretty(item)
58 58
59 59 The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
60 60 react to that or the result is an infinite loop. `p.text()` just adds
61 61 non breaking text to the output, `p.breakable()` either adds a whitespace
62 62 or breaks here. If you pass it an argument it's used instead of the
63 63 default space. `p.pretty` prettyprints another object using the pretty print
64 64 method.
65 65
66 66 The first parameter to the `group` function specifies the extra indentation
67 67 of the next line. In this example the next item will either be not
68 68 breaked (if the items are short enough) or aligned with the right edge of
69 69 the opening bracked of `MyList`.
70 70
71 71 If you want to support python 2.4 and lower you can use this code::
72 72
73 73 class MyList(list):
74 74
75 75 def _repr_pretty_(self, p, cycle):
76 76 if cycle:
77 77 p.text('MyList(...)')
78 78 else:
79 79 p.begin_group(8, 'MyList([')
80 80 for idx, item in enumerate(self):
81 81 if idx:
82 82 p.text(',')
83 83 p.breakable()
84 84 p.pretty(item)
85 85 p.end_group(8, '])')
86 86
87 87 If you just want to indent something you can use the group function
88 88 without open / close parameters. Under python 2.5 you can also use this
89 89 code::
90 90
91 91 with p.indent(2):
92 92 ...
93 93
94 94 Or under python2.4 you might want to modify ``p.indentation`` by hand but
95 95 this is rather ugly.
96 96
97 97 Inheritance diagram:
98 98
99 99 .. inheritance-diagram:: IPython.lib.pretty
100 100 :parts: 3
101 101
102 102 :copyright: 2007 by Armin Ronacher.
103 103 Portions (c) 2009 by Robert Kern.
104 104 :license: BSD License.
105 105 """
106 106 from __future__ import print_function
107 107 from contextlib import contextmanager
108 108 import sys
109 109 import types
110 110 import re
111 111 import datetime
112 112 from collections import deque
113 113
114 114 from IPython.utils.py3compat import PY3
115 115
116 116 if PY3:
117 117 from io import StringIO
118 118 else:
119 119 from StringIO import StringIO
120 120
121 121
122 122 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
123 123 'for_type', 'for_type_by_name']
124 124
125 125
126 126 _re_pattern_type = type(re.compile(''))
127 127
128 def _failed_repr(obj, e):
129 """Render a failed repr, including the exception.
130
131 Tries to get exception and type info
132 """
133 # get exception name
134 if e.__class__.__module__ in ('exceptions', 'builtins'):
135 ename = e.__class__.__name__
136 else:
137 ename = '{}.{}'.format(
138 e.__class__.__module__,
139 e.__class__.__name__,
140 )
141 # and exception string, which sometimes fails
142 # (usually due to unicode error message)
143 try:
144 estr = str(e)
145 except Exception:
146 estr = "unknown"
147
148 # and class name
149 try:
150 klass = _safe_getattr(obj, '__class__', None) or type(obj)
151 mod = _safe_getattr(klass, '__module__', None)
152 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
153 classname = klass.__name__
154 else:
155 classname = mod + '.' + klass.__name__
156 except Exception:
157 # this may be paranoid, but we already know repr is broken
158 classname = "unknown type"
159
160 # the informative repr
161 return "<repr(<{} at 0x{:x}>) failed: {}: {}>".format(
162 classname, id(obj), ename, estr,
163 )
164
165 def _safe_repr(obj):
166 """Don't assume repr is not broken."""
167 try:
168 return repr(obj)
169 except Exception as e:
170 return _failed_repr(obj, e)
171
172 def _safe_getattr(obj, attr, default=None):
173 """Safe version of getattr.
174
175 Same as getattr, but will return ``default`` on any Exception,
176 rather than raising.
177 """
178 try:
179 return getattr(obj, attr, default)
180 except Exception:
181 return default
128 182
129 183 def pretty(obj, verbose=False, max_width=79, newline='\n'):
130 184 """
131 185 Pretty print the object's representation.
132 186 """
133 187 stream = StringIO()
134 188 printer = RepresentationPrinter(stream, verbose, max_width, newline)
135 189 printer.pretty(obj)
136 190 printer.flush()
137 191 return stream.getvalue()
138 192
139 193
140 194 def pprint(obj, verbose=False, max_width=79, newline='\n'):
141 195 """
142 196 Like `pretty` but print to stdout.
143 197 """
144 198 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)
145 199 printer.pretty(obj)
146 200 printer.flush()
147 201 sys.stdout.write(newline)
148 202 sys.stdout.flush()
149 203
150 204 class _PrettyPrinterBase(object):
151 205
152 206 @contextmanager
153 207 def indent(self, indent):
154 208 """with statement support for indenting/dedenting."""
155 209 self.indentation += indent
156 210 try:
157 211 yield
158 212 finally:
159 213 self.indentation -= indent
160 214
161 215 @contextmanager
162 216 def group(self, indent=0, open='', close=''):
163 217 """like begin_group / end_group but for the with statement."""
164 218 self.begin_group(indent, open)
165 219 try:
166 220 yield
167 221 finally:
168 222 self.end_group(indent, close)
169 223
170 224 class PrettyPrinter(_PrettyPrinterBase):
171 225 """
172 226 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
173 227 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
174 228 this printer knows nothing about the default pprinters or the `_repr_pretty_`
175 229 callback method.
176 230 """
177 231
178 232 def __init__(self, output, max_width=79, newline='\n'):
179 233 self.output = output
180 234 self.max_width = max_width
181 235 self.newline = newline
182 236 self.output_width = 0
183 237 self.buffer_width = 0
184 238 self.buffer = deque()
185 239
186 240 root_group = Group(0)
187 241 self.group_stack = [root_group]
188 242 self.group_queue = GroupQueue(root_group)
189 243 self.indentation = 0
190 244
191 245 def _break_outer_groups(self):
192 246 while self.max_width < self.output_width + self.buffer_width:
193 247 group = self.group_queue.deq()
194 248 if not group:
195 249 return
196 250 while group.breakables:
197 251 x = self.buffer.popleft()
198 252 self.output_width = x.output(self.output, self.output_width)
199 253 self.buffer_width -= x.width
200 254 while self.buffer and isinstance(self.buffer[0], Text):
201 255 x = self.buffer.popleft()
202 256 self.output_width = x.output(self.output, self.output_width)
203 257 self.buffer_width -= x.width
204 258
205 259 def text(self, obj):
206 260 """Add literal text to the output."""
207 261 width = len(obj)
208 262 if self.buffer:
209 263 text = self.buffer[-1]
210 264 if not isinstance(text, Text):
211 265 text = Text()
212 266 self.buffer.append(text)
213 267 text.add(obj, width)
214 268 self.buffer_width += width
215 269 self._break_outer_groups()
216 270 else:
217 271 self.output.write(obj)
218 272 self.output_width += width
219 273
220 274 def breakable(self, sep=' '):
221 275 """
222 276 Add a breakable separator to the output. This does not mean that it
223 277 will automatically break here. If no breaking on this position takes
224 278 place the `sep` is inserted which default to one space.
225 279 """
226 280 width = len(sep)
227 281 group = self.group_stack[-1]
228 282 if group.want_break:
229 283 self.flush()
230 284 self.output.write(self.newline)
231 285 self.output.write(' ' * self.indentation)
232 286 self.output_width = self.indentation
233 287 self.buffer_width = 0
234 288 else:
235 289 self.buffer.append(Breakable(sep, width, self))
236 290 self.buffer_width += width
237 291 self._break_outer_groups()
238 292
239 293 def break_(self):
240 294 """
241 295 Explicitly insert a newline into the output, maintaining correct indentation.
242 296 """
243 297 self.flush()
244 298 self.output.write(self.newline)
245 299 self.output.write(' ' * self.indentation)
246 300 self.output_width = self.indentation
247 301 self.buffer_width = 0
248 302
249 303
250 304 def begin_group(self, indent=0, open=''):
251 305 """
252 306 Begin a group. If you want support for python < 2.5 which doesn't has
253 307 the with statement this is the preferred way:
254 308
255 309 p.begin_group(1, '{')
256 310 ...
257 311 p.end_group(1, '}')
258 312
259 313 The python 2.5 expression would be this:
260 314
261 315 with p.group(1, '{', '}'):
262 316 ...
263 317
264 318 The first parameter specifies the indentation for the next line (usually
265 319 the width of the opening text), the second the opening text. All
266 320 parameters are optional.
267 321 """
268 322 if open:
269 323 self.text(open)
270 324 group = Group(self.group_stack[-1].depth + 1)
271 325 self.group_stack.append(group)
272 326 self.group_queue.enq(group)
273 327 self.indentation += indent
274 328
275 329 def end_group(self, dedent=0, close=''):
276 330 """End a group. See `begin_group` for more details."""
277 331 self.indentation -= dedent
278 332 group = self.group_stack.pop()
279 333 if not group.breakables:
280 334 self.group_queue.remove(group)
281 335 if close:
282 336 self.text(close)
283 337
284 338 def flush(self):
285 339 """Flush data that is left in the buffer."""
286 340 for data in self.buffer:
287 341 self.output_width += data.output(self.output, self.output_width)
288 342 self.buffer.clear()
289 343 self.buffer_width = 0
290 344
291 345
292 346 def _get_mro(obj_class):
293 347 """ Get a reasonable method resolution order of a class and its superclasses
294 348 for both old-style and new-style classes.
295 349 """
296 350 if not hasattr(obj_class, '__mro__'):
297 351 # Old-style class. Mix in object to make a fake new-style class.
298 352 try:
299 353 obj_class = type(obj_class.__name__, (obj_class, object), {})
300 354 except TypeError:
301 355 # Old-style extension type that does not descend from object.
302 356 # FIXME: try to construct a more thorough MRO.
303 357 mro = [obj_class]
304 358 else:
305 359 mro = obj_class.__mro__[1:-1]
306 360 else:
307 361 mro = obj_class.__mro__
308 362 return mro
309 363
310 364
311 365 class RepresentationPrinter(PrettyPrinter):
312 366 """
313 367 Special pretty printer that has a `pretty` method that calls the pretty
314 368 printer for a python object.
315 369
316 370 This class stores processing data on `self` so you must *never* use
317 371 this class in a threaded environment. Always lock it or reinstanciate
318 372 it.
319 373
320 374 Instances also have a verbose flag callbacks can access to control their
321 375 output. For example the default instance repr prints all attributes and
322 376 methods that are not prefixed by an underscore if the printer is in
323 377 verbose mode.
324 378 """
325 379
326 380 def __init__(self, output, verbose=False, max_width=79, newline='\n',
327 381 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None):
328 382
329 383 PrettyPrinter.__init__(self, output, max_width, newline)
330 384 self.verbose = verbose
331 385 self.stack = []
332 386 if singleton_pprinters is None:
333 387 singleton_pprinters = _singleton_pprinters.copy()
334 388 self.singleton_pprinters = singleton_pprinters
335 389 if type_pprinters is None:
336 390 type_pprinters = _type_pprinters.copy()
337 391 self.type_pprinters = type_pprinters
338 392 if deferred_pprinters is None:
339 393 deferred_pprinters = _deferred_type_pprinters.copy()
340 394 self.deferred_pprinters = deferred_pprinters
341 395
342 396 def pretty(self, obj):
343 397 """Pretty print the given object."""
344 398 obj_id = id(obj)
345 399 cycle = obj_id in self.stack
346 400 self.stack.append(obj_id)
347 401 self.begin_group()
348 402 try:
349 obj_class = getattr(obj, '__class__', None) or type(obj)
403 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
350 404 # First try to find registered singleton printers for the type.
351 405 try:
352 406 printer = self.singleton_pprinters[obj_id]
353 407 except (TypeError, KeyError):
354 408 pass
355 409 else:
356 410 return printer(obj, self, cycle)
357 411 # Next walk the mro and check for either:
358 412 # 1) a registered printer
359 413 # 2) a _repr_pretty_ method
360 414 for cls in _get_mro(obj_class):
361 415 if cls in self.type_pprinters:
362 416 # printer registered in self.type_pprinters
363 417 return self.type_pprinters[cls](obj, self, cycle)
364 418 else:
365 419 # deferred printer
366 420 printer = self._in_deferred_types(cls)
367 421 if printer is not None:
368 422 return printer(obj, self, cycle)
369 423 else:
370 424 # Finally look for special method names.
371 425 # Some objects automatically create any requested
372 426 # attribute. Try to ignore most of them by checking for
373 427 # callability.
374 428 if '_repr_pretty_' in cls.__dict__:
375 429 meth = cls._repr_pretty_
376 430 if callable(meth):
377 431 return meth(obj, self, cycle)
378 432 return _default_pprint(obj, self, cycle)
379 433 finally:
380 434 self.end_group()
381 435 self.stack.pop()
382 436
383 437 def _in_deferred_types(self, cls):
384 438 """
385 439 Check if the given class is specified in the deferred type registry.
386 440
387 441 Returns the printer from the registry if it exists, and None if the
388 442 class is not in the registry. Successful matches will be moved to the
389 443 regular type registry for future use.
390 444 """
391 mod = getattr(cls, '__module__', None)
392 name = getattr(cls, '__name__', None)
445 mod = _safe_getattr(cls, '__module__', None)
446 name = _safe_getattr(cls, '__name__', None)
393 447 key = (mod, name)
394 448 printer = None
395 449 if key in self.deferred_pprinters:
396 450 # Move the printer over to the regular registry.
397 451 printer = self.deferred_pprinters.pop(key)
398 452 self.type_pprinters[cls] = printer
399 453 return printer
400 454
401 455
402 456 class Printable(object):
403 457
404 458 def output(self, stream, output_width):
405 459 return output_width
406 460
407 461
408 462 class Text(Printable):
409 463
410 464 def __init__(self):
411 465 self.objs = []
412 466 self.width = 0
413 467
414 468 def output(self, stream, output_width):
415 469 for obj in self.objs:
416 470 stream.write(obj)
417 471 return output_width + self.width
418 472
419 473 def add(self, obj, width):
420 474 self.objs.append(obj)
421 475 self.width += width
422 476
423 477
424 478 class Breakable(Printable):
425 479
426 480 def __init__(self, seq, width, pretty):
427 481 self.obj = seq
428 482 self.width = width
429 483 self.pretty = pretty
430 484 self.indentation = pretty.indentation
431 485 self.group = pretty.group_stack[-1]
432 486 self.group.breakables.append(self)
433 487
434 488 def output(self, stream, output_width):
435 489 self.group.breakables.popleft()
436 490 if self.group.want_break:
437 491 stream.write(self.pretty.newline)
438 492 stream.write(' ' * self.indentation)
439 493 return self.indentation
440 494 if not self.group.breakables:
441 495 self.pretty.group_queue.remove(self.group)
442 496 stream.write(self.obj)
443 497 return output_width + self.width
444 498
445 499
446 500 class Group(Printable):
447 501
448 502 def __init__(self, depth):
449 503 self.depth = depth
450 504 self.breakables = deque()
451 505 self.want_break = False
452 506
453 507
454 508 class GroupQueue(object):
455 509
456 510 def __init__(self, *groups):
457 511 self.queue = []
458 512 for group in groups:
459 513 self.enq(group)
460 514
461 515 def enq(self, group):
462 516 depth = group.depth
463 517 while depth > len(self.queue) - 1:
464 518 self.queue.append([])
465 519 self.queue[depth].append(group)
466 520
467 521 def deq(self):
468 522 for stack in self.queue:
469 523 for idx, group in enumerate(reversed(stack)):
470 524 if group.breakables:
471 525 del stack[idx]
472 526 group.want_break = True
473 527 return group
474 528 for group in stack:
475 529 group.want_break = True
476 530 del stack[:]
477 531
478 532 def remove(self, group):
479 533 try:
480 534 self.queue[group.depth].remove(group)
481 535 except ValueError:
482 536 pass
483 537
484 538 try:
485 539 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
486 540 except AttributeError: # Python 3
487 541 _baseclass_reprs = (object.__repr__,)
488 542
489 543
490 544 def _default_pprint(obj, p, cycle):
491 545 """
492 546 The default print function. Used if an object does not provide one and
493 547 it's none of the builtin objects.
494 548 """
495 klass = getattr(obj, '__class__', None) or type(obj)
496 if getattr(klass, '__repr__', None) not in _baseclass_reprs:
549 klass = _safe_getattr(obj, '__class__', None) or type(obj)
550 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
497 551 # A user-provided repr. Find newlines and replace them with p.break_()
498 output = repr(obj)
552 output = _safe_repr(obj)
499 553 for idx,output_line in enumerate(output.splitlines()):
500 554 if idx:
501 555 p.break_()
502 556 p.text(output_line)
503 557 return
504 558 p.begin_group(1, '<')
505 559 p.pretty(klass)
506 560 p.text(' at 0x%x' % id(obj))
507 561 if cycle:
508 562 p.text(' ...')
509 563 elif p.verbose:
510 564 first = True
511 565 for key in dir(obj):
512 566 if not key.startswith('_'):
513 567 try:
514 568 value = getattr(obj, key)
515 569 except AttributeError:
516 570 continue
517 571 if isinstance(value, types.MethodType):
518 572 continue
519 573 if not first:
520 574 p.text(',')
521 575 p.breakable()
522 576 p.text(key)
523 577 p.text('=')
524 578 step = len(key) + 1
525 579 p.indentation += step
526 580 p.pretty(value)
527 581 p.indentation -= step
528 582 first = False
529 583 p.end_group(1, '>')
530 584
531 585
532 586 def _seq_pprinter_factory(start, end, basetype):
533 587 """
534 588 Factory that returns a pprint function useful for sequences. Used by
535 589 the default pprint for tuples, dicts, and lists.
536 590 """
537 591 def inner(obj, p, cycle):
538 592 typ = type(obj)
539 593 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
540 594 # If the subclass provides its own repr, use it instead.
541 595 return p.text(typ.__repr__(obj))
542 596
543 597 if cycle:
544 598 return p.text(start + '...' + end)
545 599 step = len(start)
546 600 p.begin_group(step, start)
547 601 for idx, x in enumerate(obj):
548 602 if idx:
549 603 p.text(',')
550 604 p.breakable()
551 605 p.pretty(x)
552 606 if len(obj) == 1 and type(obj) is tuple:
553 607 # Special case for 1-item tuples.
554 608 p.text(',')
555 609 p.end_group(step, end)
556 610 return inner
557 611
558 612
559 613 def _set_pprinter_factory(start, end, basetype):
560 614 """
561 615 Factory that returns a pprint function useful for sets and frozensets.
562 616 """
563 617 def inner(obj, p, cycle):
564 618 typ = type(obj)
565 619 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
566 620 # If the subclass provides its own repr, use it instead.
567 621 return p.text(typ.__repr__(obj))
568 622
569 623 if cycle:
570 624 return p.text(start + '...' + end)
571 625 if len(obj) == 0:
572 626 # Special case.
573 627 p.text(basetype.__name__ + '()')
574 628 else:
575 629 step = len(start)
576 630 p.begin_group(step, start)
577 631 # Like dictionary keys, we will try to sort the items.
578 632 items = list(obj)
579 633 try:
580 634 items.sort()
581 635 except Exception:
582 636 # Sometimes the items don't sort.
583 637 pass
584 638 for idx, x in enumerate(items):
585 639 if idx:
586 640 p.text(',')
587 641 p.breakable()
588 642 p.pretty(x)
589 643 p.end_group(step, end)
590 644 return inner
591 645
592 646
593 647 def _dict_pprinter_factory(start, end, basetype=None):
594 648 """
595 649 Factory that returns a pprint function used by the default pprint of
596 650 dicts and dict proxies.
597 651 """
598 652 def inner(obj, p, cycle):
599 653 typ = type(obj)
600 654 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
601 655 # If the subclass provides its own repr, use it instead.
602 656 return p.text(typ.__repr__(obj))
603 657
604 658 if cycle:
605 659 return p.text('{...}')
606 660 p.begin_group(1, start)
607 661 keys = obj.keys()
608 662 try:
609 663 keys.sort()
610 664 except Exception as e:
611 665 # Sometimes the keys don't sort.
612 666 pass
613 667 for idx, key in enumerate(keys):
614 668 if idx:
615 669 p.text(',')
616 670 p.breakable()
617 671 p.pretty(key)
618 672 p.text(': ')
619 673 p.pretty(obj[key])
620 674 p.end_group(1, end)
621 675 return inner
622 676
623 677
624 678 def _super_pprint(obj, p, cycle):
625 679 """The pprint for the super type."""
626 680 p.begin_group(8, '<super: ')
627 681 p.pretty(obj.__self_class__)
628 682 p.text(',')
629 683 p.breakable()
630 684 p.pretty(obj.__self__)
631 685 p.end_group(8, '>')
632 686
633 687
634 688 def _re_pattern_pprint(obj, p, cycle):
635 689 """The pprint function for regular expression patterns."""
636 690 p.text('re.compile(')
637 691 pattern = repr(obj.pattern)
638 692 if pattern[:1] in 'uU':
639 693 pattern = pattern[1:]
640 694 prefix = 'ur'
641 695 else:
642 696 prefix = 'r'
643 697 pattern = prefix + pattern.replace('\\\\', '\\')
644 698 p.text(pattern)
645 699 if obj.flags:
646 700 p.text(',')
647 701 p.breakable()
648 702 done_one = False
649 703 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
650 704 'UNICODE', 'VERBOSE', 'DEBUG'):
651 705 if obj.flags & getattr(re, flag):
652 706 if done_one:
653 707 p.text('|')
654 708 p.text('re.' + flag)
655 709 done_one = True
656 710 p.text(')')
657 711
658 712
659 713 def _type_pprint(obj, p, cycle):
660 714 """The pprint for classes and types."""
661 mod = getattr(obj, '__module__', None)
715 mod = _safe_getattr(obj, '__module__', None)
662 716 if mod is None:
663 717 # Heap allocated types might not have the module attribute,
664 718 # and others may set it to None.
665 719 return p.text(obj.__name__)
666 720
667 721 if mod in ('__builtin__', 'builtins', 'exceptions'):
668 722 name = obj.__name__
669 723 else:
670 724 name = mod + '.' + obj.__name__
671 725 p.text(name)
672 726
673 727
674 728 def _repr_pprint(obj, p, cycle):
675 729 """A pprint that just redirects to the normal repr function."""
676 p.text(repr(obj))
730 p.text(_safe_repr(obj))
677 731
678 732
679 733 def _function_pprint(obj, p, cycle):
680 734 """Base pprint for all functions and builtin functions."""
681 735 if obj.__module__ in ('__builtin__', 'builtins', 'exceptions') or not obj.__module__:
682 736 name = obj.__name__
683 737 else:
684 738 name = obj.__module__ + '.' + obj.__name__
685 739 p.text('<function %s>' % name)
686 740
687 741
688 742 def _exception_pprint(obj, p, cycle):
689 743 """Base pprint for all exceptions."""
690 744 if obj.__class__.__module__ in ('exceptions', 'builtins'):
691 745 name = obj.__class__.__name__
692 746 else:
693 747 name = '%s.%s' % (
694 748 obj.__class__.__module__,
695 749 obj.__class__.__name__
696 750 )
697 751 step = len(name) + 1
698 752 p.begin_group(step, name + '(')
699 753 for idx, arg in enumerate(getattr(obj, 'args', ())):
700 754 if idx:
701 755 p.text(',')
702 756 p.breakable()
703 757 p.pretty(arg)
704 758 p.end_group(step, ')')
705 759
706 760
707 761 #: the exception base
708 762 try:
709 763 _exception_base = BaseException
710 764 except NameError:
711 765 _exception_base = Exception
712 766
713 767
714 768 #: printers for builtin types
715 769 _type_pprinters = {
716 770 int: _repr_pprint,
717 771 float: _repr_pprint,
718 772 str: _repr_pprint,
719 773 tuple: _seq_pprinter_factory('(', ')', tuple),
720 774 list: _seq_pprinter_factory('[', ']', list),
721 775 dict: _dict_pprinter_factory('{', '}', dict),
722 776
723 777 set: _set_pprinter_factory('{', '}', set),
724 778 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
725 779 super: _super_pprint,
726 780 _re_pattern_type: _re_pattern_pprint,
727 781 type: _type_pprint,
728 782 types.FunctionType: _function_pprint,
729 783 types.BuiltinFunctionType: _function_pprint,
730 784 types.MethodType: _repr_pprint,
731 785
732 786 datetime.datetime: _repr_pprint,
733 787 datetime.timedelta: _repr_pprint,
734 788 _exception_base: _exception_pprint
735 789 }
736 790
737 791 try:
738 792 _type_pprinters[types.DictProxyType] = _dict_pprinter_factory('<dictproxy {', '}>')
739 793 _type_pprinters[types.ClassType] = _type_pprint
740 794 _type_pprinters[types.SliceType] = _repr_pprint
741 795 except AttributeError: # Python 3
742 796 _type_pprinters[slice] = _repr_pprint
743 797
744 798 try:
745 799 _type_pprinters[xrange] = _repr_pprint
746 800 _type_pprinters[long] = _repr_pprint
747 801 _type_pprinters[unicode] = _repr_pprint
748 802 except NameError:
749 803 _type_pprinters[range] = _repr_pprint
750 804 _type_pprinters[bytes] = _repr_pprint
751 805
752 806 #: printers for types specified by name
753 807 _deferred_type_pprinters = {
754 808 }
755 809
756 810 def for_type(typ, func):
757 811 """
758 812 Add a pretty printer for a given type.
759 813 """
760 814 oldfunc = _type_pprinters.get(typ, None)
761 815 if func is not None:
762 816 # To support easy restoration of old pprinters, we need to ignore Nones.
763 817 _type_pprinters[typ] = func
764 818 return oldfunc
765 819
766 820 def for_type_by_name(type_module, type_name, func):
767 821 """
768 822 Add a pretty printer for a type specified by the module and name of a type
769 823 rather than the type object itself.
770 824 """
771 825 key = (type_module, type_name)
772 826 oldfunc = _deferred_type_pprinters.get(key, None)
773 827 if func is not None:
774 828 # To support easy restoration of old pprinters, we need to ignore Nones.
775 829 _deferred_type_pprinters[key] = func
776 830 return oldfunc
777 831
778 832
779 833 #: printers for the default singletons
780 834 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
781 835 NotImplemented]), _repr_pprint)
782 836
783 837
784 838 if __name__ == '__main__':
785 839 from random import randrange
786 840 class Foo(object):
787 841 def __init__(self):
788 842 self.foo = 1
789 843 self.bar = re.compile(r'\s+')
790 844 self.blub = dict.fromkeys(range(30), randrange(1, 40))
791 845 self.hehe = 23424.234234
792 846 self.list = ["blub", "blah", self]
793 847
794 848 def get_foo(self):
795 849 print("foo")
796 850
797 851 pprint(Foo(), verbose=True)
@@ -1,153 +1,184 b''
1 1 """Tests for IPython.lib.pretty.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2011, the IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14 from __future__ import print_function
15 15
16 16 # Third-party imports
17 17 import nose.tools as nt
18 18
19 19 # Our own imports
20 20 from IPython.lib import pretty
21 21 from IPython.testing.decorators import skip_without
22 22
23 23 #-----------------------------------------------------------------------------
24 24 # Classes and functions
25 25 #-----------------------------------------------------------------------------
26 26
27 27 class MyList(object):
28 28 def __init__(self, content):
29 29 self.content = content
30 30 def _repr_pretty_(self, p, cycle):
31 31 if cycle:
32 32 p.text("MyList(...)")
33 33 else:
34 34 with p.group(3, "MyList(", ")"):
35 35 for (i, child) in enumerate(self.content):
36 36 if i:
37 37 p.text(",")
38 38 p.breakable()
39 39 else:
40 40 p.breakable("")
41 41 p.pretty(child)
42 42
43 43
44 44 class MyDict(dict):
45 45 def _repr_pretty_(self, p, cycle):
46 46 p.text("MyDict(...)")
47 47
48 48
49 49 class Dummy1(object):
50 50 def _repr_pretty_(self, p, cycle):
51 51 p.text("Dummy1(...)")
52 52
53 53 class Dummy2(Dummy1):
54 54 _repr_pretty_ = None
55 55
56 56 class NoModule(object):
57 57 pass
58 58
59 59 NoModule.__module__ = None
60 60
61 61 class Breaking(object):
62 62 def _repr_pretty_(self, p, cycle):
63 63 with p.group(4,"TG: ",":"):
64 64 p.text("Breaking(")
65 65 p.break_()
66 66 p.text(")")
67 67
68 68 class BreakingRepr(object):
69 69 def __repr__(self):
70 70 return "Breaking(\n)"
71 71
72 72 class BreakingReprParent(object):
73 73 def _repr_pretty_(self, p, cycle):
74 74 with p.group(4,"TG: ",":"):
75 75 p.pretty(BreakingRepr())
76 76
77 class BadRepr(object):
78
79 def __repr__(self):
80 return 1/0
77 81
78 82
79 83 def test_indentation():
80 84 """Test correct indentation in groups"""
81 85 count = 40
82 86 gotoutput = pretty.pretty(MyList(range(count)))
83 87 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
84 88
85 89 nt.assert_equal(gotoutput, expectedoutput)
86 90
87 91
88 92 def test_dispatch():
89 93 """
90 94 Test correct dispatching: The _repr_pretty_ method for MyDict
91 95 must be found before the registered printer for dict.
92 96 """
93 97 gotoutput = pretty.pretty(MyDict())
94 98 expectedoutput = "MyDict(...)"
95 99
96 100 nt.assert_equal(gotoutput, expectedoutput)
97 101
98 102
99 103 def test_callability_checking():
100 104 """
101 105 Test that the _repr_pretty_ method is tested for callability and skipped if
102 106 not.
103 107 """
104 108 gotoutput = pretty.pretty(Dummy2())
105 109 expectedoutput = "Dummy1(...)"
106 110
107 111 nt.assert_equal(gotoutput, expectedoutput)
108 112
109 113
110 114 def test_sets():
111 115 """
112 116 Test that set and frozenset use Python 3 formatting.
113 117 """
114 118 objects = [set(), frozenset(), set([1]), frozenset([1]), set([1, 2]),
115 119 frozenset([1, 2]), set([-1, -2, -3])]
116 120 expected = ['set()', 'frozenset()', '{1}', 'frozenset({1})', '{1, 2}',
117 121 'frozenset({1, 2})', '{-3, -2, -1}']
118 122 for obj, expected_output in zip(objects, expected):
119 123 got_output = pretty.pretty(obj)
120 124 yield nt.assert_equal, got_output, expected_output
121 125
122 126
123 127 @skip_without('xxlimited')
124 128 def test_pprint_heap_allocated_type():
125 129 """
126 130 Test that pprint works for heap allocated types.
127 131 """
128 132 import xxlimited
129 133 output = pretty.pretty(xxlimited.Null)
130 134 nt.assert_equal(output, 'xxlimited.Null')
131 135
132 136 def test_pprint_nomod():
133 137 """
134 138 Test that pprint works for classes with no __module__.
135 139 """
136 140 output = pretty.pretty(NoModule)
137 141 nt.assert_equal(output, 'NoModule')
138 142
139 143 def test_pprint_break():
140 144 """
141 145 Test that p.break_ produces expected output
142 146 """
143 147 output = pretty.pretty(Breaking())
144 148 expected = "TG: Breaking(\n ):"
145 149 nt.assert_equal(output, expected)
146 150
147 151 def test_pprint_break_repr():
148 152 """
149 153 Test that p.break_ is used in repr
150 154 """
151 155 output = pretty.pretty(BreakingReprParent())
152 156 expected = "TG: Breaking(\n ):"
153 157 nt.assert_equal(output, expected)
158
159 def test_bad_repr():
160 """Don't raise, even when repr fails"""
161 output = pretty.pretty(BadRepr())
162 nt.assert_in("failed", output)
163 nt.assert_in("at 0x", output)
164 nt.assert_in("test_pretty", output)
165
166 class BadException(Exception):
167 def __str__(self):
168 return -1
169
170 class ReallyBadRepr(object):
171 __module__ = 1
172 @property
173 def __class__(self):
174 raise ValueError("I am horrible")
175
176 def __repr__(self):
177 raise BadException()
178
179 def test_really_bad_repr():
180 output = pretty.pretty(ReallyBadRepr())
181 nt.assert_in("failed", output)
182 nt.assert_in("BadException: unknown", output)
183 nt.assert_in("unknown type", output)
184 No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now