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