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