##// END OF EJS Templates
Deprecate CUnicodeIO...
Thomas Kluyver -
Show More
@@ -1,857 +1,863 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 86 from io import StringIO
87 from warnings import warn
87 88
88 89 from IPython.utils.py3compat import PYPY, cast_unicode
89 90 from IPython.utils.encoding import get_stream_enc
90 91
91 92
92 93 __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
93 94 'for_type', 'for_type_by_name']
94 95
95 96
96 97 MAX_SEQ_LENGTH = 1000
97 98 _re_pattern_type = type(re.compile(''))
98 99
99 100 def _safe_getattr(obj, attr, default=None):
100 101 """Safe version of getattr.
101 102
102 103 Same as getattr, but will return ``default`` on any Exception,
103 104 rather than raising.
104 105 """
105 106 try:
106 107 return getattr(obj, attr, default)
107 108 except Exception:
108 109 return default
109 110
110 CUnicodeIO = StringIO
111 class CUnicodeIO(StringIO):
112 def __init__(self, *args, **kwargs):
113 super().__init__(*args, **kwargs)
114 warn(("CUnicodeIO is deprecated since IPython 6.0. "
115 "Please use io.StringIO instead."),
116 DeprecationWarning, stacklevel=2)
111 117
112 118 def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
113 119 """
114 120 Pretty print the object's representation.
115 121 """
116 122 stream = StringIO()
117 123 printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
118 124 printer.pretty(obj)
119 125 printer.flush()
120 126 return stream.getvalue()
121 127
122 128
123 129 def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
124 130 """
125 131 Like `pretty` but print to stdout.
126 132 """
127 133 printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
128 134 printer.pretty(obj)
129 135 printer.flush()
130 136 sys.stdout.write(newline)
131 137 sys.stdout.flush()
132 138
133 139 class _PrettyPrinterBase(object):
134 140
135 141 @contextmanager
136 142 def indent(self, indent):
137 143 """with statement support for indenting/dedenting."""
138 144 self.indentation += indent
139 145 try:
140 146 yield
141 147 finally:
142 148 self.indentation -= indent
143 149
144 150 @contextmanager
145 151 def group(self, indent=0, open='', close=''):
146 152 """like begin_group / end_group but for the with statement."""
147 153 self.begin_group(indent, open)
148 154 try:
149 155 yield
150 156 finally:
151 157 self.end_group(indent, close)
152 158
153 159 class PrettyPrinter(_PrettyPrinterBase):
154 160 """
155 161 Baseclass for the `RepresentationPrinter` prettyprinter that is used to
156 162 generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
157 163 this printer knows nothing about the default pprinters or the `_repr_pretty_`
158 164 callback method.
159 165 """
160 166
161 167 def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
162 168 self.output = output
163 169 self.max_width = max_width
164 170 self.newline = newline
165 171 self.max_seq_length = max_seq_length
166 172 self.output_width = 0
167 173 self.buffer_width = 0
168 174 self.buffer = deque()
169 175
170 176 root_group = Group(0)
171 177 self.group_stack = [root_group]
172 178 self.group_queue = GroupQueue(root_group)
173 179 self.indentation = 0
174 180
175 181 def _break_outer_groups(self):
176 182 while self.max_width < self.output_width + self.buffer_width:
177 183 group = self.group_queue.deq()
178 184 if not group:
179 185 return
180 186 while group.breakables:
181 187 x = self.buffer.popleft()
182 188 self.output_width = x.output(self.output, self.output_width)
183 189 self.buffer_width -= x.width
184 190 while self.buffer and isinstance(self.buffer[0], Text):
185 191 x = self.buffer.popleft()
186 192 self.output_width = x.output(self.output, self.output_width)
187 193 self.buffer_width -= x.width
188 194
189 195 def text(self, obj):
190 196 """Add literal text to the output."""
191 197 width = len(obj)
192 198 if self.buffer:
193 199 text = self.buffer[-1]
194 200 if not isinstance(text, Text):
195 201 text = Text()
196 202 self.buffer.append(text)
197 203 text.add(obj, width)
198 204 self.buffer_width += width
199 205 self._break_outer_groups()
200 206 else:
201 207 self.output.write(obj)
202 208 self.output_width += width
203 209
204 210 def breakable(self, sep=' '):
205 211 """
206 212 Add a breakable separator to the output. This does not mean that it
207 213 will automatically break here. If no breaking on this position takes
208 214 place the `sep` is inserted which default to one space.
209 215 """
210 216 width = len(sep)
211 217 group = self.group_stack[-1]
212 218 if group.want_break:
213 219 self.flush()
214 220 self.output.write(self.newline)
215 221 self.output.write(' ' * self.indentation)
216 222 self.output_width = self.indentation
217 223 self.buffer_width = 0
218 224 else:
219 225 self.buffer.append(Breakable(sep, width, self))
220 226 self.buffer_width += width
221 227 self._break_outer_groups()
222 228
223 229 def break_(self):
224 230 """
225 231 Explicitly insert a newline into the output, maintaining correct indentation.
226 232 """
227 233 self.flush()
228 234 self.output.write(self.newline)
229 235 self.output.write(' ' * self.indentation)
230 236 self.output_width = self.indentation
231 237 self.buffer_width = 0
232 238
233 239
234 240 def begin_group(self, indent=0, open=''):
235 241 """
236 242 Begin a group. If you want support for python < 2.5 which doesn't has
237 243 the with statement this is the preferred way:
238 244
239 245 p.begin_group(1, '{')
240 246 ...
241 247 p.end_group(1, '}')
242 248
243 249 The python 2.5 expression would be this:
244 250
245 251 with p.group(1, '{', '}'):
246 252 ...
247 253
248 254 The first parameter specifies the indentation for the next line (usually
249 255 the width of the opening text), the second the opening text. All
250 256 parameters are optional.
251 257 """
252 258 if open:
253 259 self.text(open)
254 260 group = Group(self.group_stack[-1].depth + 1)
255 261 self.group_stack.append(group)
256 262 self.group_queue.enq(group)
257 263 self.indentation += indent
258 264
259 265 def _enumerate(self, seq):
260 266 """like enumerate, but with an upper limit on the number of items"""
261 267 for idx, x in enumerate(seq):
262 268 if self.max_seq_length and idx >= self.max_seq_length:
263 269 self.text(',')
264 270 self.breakable()
265 271 self.text('...')
266 272 return
267 273 yield idx, x
268 274
269 275 def end_group(self, dedent=0, close=''):
270 276 """End a group. See `begin_group` for more details."""
271 277 self.indentation -= dedent
272 278 group = self.group_stack.pop()
273 279 if not group.breakables:
274 280 self.group_queue.remove(group)
275 281 if close:
276 282 self.text(close)
277 283
278 284 def flush(self):
279 285 """Flush data that is left in the buffer."""
280 286 for data in self.buffer:
281 287 self.output_width += data.output(self.output, self.output_width)
282 288 self.buffer.clear()
283 289 self.buffer_width = 0
284 290
285 291
286 292 def _get_mro(obj_class):
287 293 """ Get a reasonable method resolution order of a class and its superclasses
288 294 for both old-style and new-style classes.
289 295 """
290 296 if not hasattr(obj_class, '__mro__'):
291 297 # Old-style class. Mix in object to make a fake new-style class.
292 298 try:
293 299 obj_class = type(obj_class.__name__, (obj_class, object), {})
294 300 except TypeError:
295 301 # Old-style extension type that does not descend from object.
296 302 # FIXME: try to construct a more thorough MRO.
297 303 mro = [obj_class]
298 304 else:
299 305 mro = obj_class.__mro__[1:-1]
300 306 else:
301 307 mro = obj_class.__mro__
302 308 return mro
303 309
304 310
305 311 class RepresentationPrinter(PrettyPrinter):
306 312 """
307 313 Special pretty printer that has a `pretty` method that calls the pretty
308 314 printer for a python object.
309 315
310 316 This class stores processing data on `self` so you must *never* use
311 317 this class in a threaded environment. Always lock it or reinstanciate
312 318 it.
313 319
314 320 Instances also have a verbose flag callbacks can access to control their
315 321 output. For example the default instance repr prints all attributes and
316 322 methods that are not prefixed by an underscore if the printer is in
317 323 verbose mode.
318 324 """
319 325
320 326 def __init__(self, output, verbose=False, max_width=79, newline='\n',
321 327 singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
322 328 max_seq_length=MAX_SEQ_LENGTH):
323 329
324 330 PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
325 331 self.verbose = verbose
326 332 self.stack = []
327 333 if singleton_pprinters is None:
328 334 singleton_pprinters = _singleton_pprinters.copy()
329 335 self.singleton_pprinters = singleton_pprinters
330 336 if type_pprinters is None:
331 337 type_pprinters = _type_pprinters.copy()
332 338 self.type_pprinters = type_pprinters
333 339 if deferred_pprinters is None:
334 340 deferred_pprinters = _deferred_type_pprinters.copy()
335 341 self.deferred_pprinters = deferred_pprinters
336 342
337 343 def pretty(self, obj):
338 344 """Pretty print the given object."""
339 345 obj_id = id(obj)
340 346 cycle = obj_id in self.stack
341 347 self.stack.append(obj_id)
342 348 self.begin_group()
343 349 try:
344 350 obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
345 351 # First try to find registered singleton printers for the type.
346 352 try:
347 353 printer = self.singleton_pprinters[obj_id]
348 354 except (TypeError, KeyError):
349 355 pass
350 356 else:
351 357 return printer(obj, self, cycle)
352 358 # Next walk the mro and check for either:
353 359 # 1) a registered printer
354 360 # 2) a _repr_pretty_ method
355 361 for cls in _get_mro(obj_class):
356 362 if cls in self.type_pprinters:
357 363 # printer registered in self.type_pprinters
358 364 return self.type_pprinters[cls](obj, self, cycle)
359 365 else:
360 366 # deferred printer
361 367 printer = self._in_deferred_types(cls)
362 368 if printer is not None:
363 369 return printer(obj, self, cycle)
364 370 else:
365 371 # Finally look for special method names.
366 372 # Some objects automatically create any requested
367 373 # attribute. Try to ignore most of them by checking for
368 374 # callability.
369 375 if '_repr_pretty_' in cls.__dict__:
370 376 meth = cls._repr_pretty_
371 377 if callable(meth):
372 378 return meth(obj, self, cycle)
373 379 return _default_pprint(obj, self, cycle)
374 380 finally:
375 381 self.end_group()
376 382 self.stack.pop()
377 383
378 384 def _in_deferred_types(self, cls):
379 385 """
380 386 Check if the given class is specified in the deferred type registry.
381 387
382 388 Returns the printer from the registry if it exists, and None if the
383 389 class is not in the registry. Successful matches will be moved to the
384 390 regular type registry for future use.
385 391 """
386 392 mod = _safe_getattr(cls, '__module__', None)
387 393 name = _safe_getattr(cls, '__name__', None)
388 394 key = (mod, name)
389 395 printer = None
390 396 if key in self.deferred_pprinters:
391 397 # Move the printer over to the regular registry.
392 398 printer = self.deferred_pprinters.pop(key)
393 399 self.type_pprinters[cls] = printer
394 400 return printer
395 401
396 402
397 403 class Printable(object):
398 404
399 405 def output(self, stream, output_width):
400 406 return output_width
401 407
402 408
403 409 class Text(Printable):
404 410
405 411 def __init__(self):
406 412 self.objs = []
407 413 self.width = 0
408 414
409 415 def output(self, stream, output_width):
410 416 for obj in self.objs:
411 417 stream.write(obj)
412 418 return output_width + self.width
413 419
414 420 def add(self, obj, width):
415 421 self.objs.append(obj)
416 422 self.width += width
417 423
418 424
419 425 class Breakable(Printable):
420 426
421 427 def __init__(self, seq, width, pretty):
422 428 self.obj = seq
423 429 self.width = width
424 430 self.pretty = pretty
425 431 self.indentation = pretty.indentation
426 432 self.group = pretty.group_stack[-1]
427 433 self.group.breakables.append(self)
428 434
429 435 def output(self, stream, output_width):
430 436 self.group.breakables.popleft()
431 437 if self.group.want_break:
432 438 stream.write(self.pretty.newline)
433 439 stream.write(' ' * self.indentation)
434 440 return self.indentation
435 441 if not self.group.breakables:
436 442 self.pretty.group_queue.remove(self.group)
437 443 stream.write(self.obj)
438 444 return output_width + self.width
439 445
440 446
441 447 class Group(Printable):
442 448
443 449 def __init__(self, depth):
444 450 self.depth = depth
445 451 self.breakables = deque()
446 452 self.want_break = False
447 453
448 454
449 455 class GroupQueue(object):
450 456
451 457 def __init__(self, *groups):
452 458 self.queue = []
453 459 for group in groups:
454 460 self.enq(group)
455 461
456 462 def enq(self, group):
457 463 depth = group.depth
458 464 while depth > len(self.queue) - 1:
459 465 self.queue.append([])
460 466 self.queue[depth].append(group)
461 467
462 468 def deq(self):
463 469 for stack in self.queue:
464 470 for idx, group in enumerate(reversed(stack)):
465 471 if group.breakables:
466 472 del stack[idx]
467 473 group.want_break = True
468 474 return group
469 475 for group in stack:
470 476 group.want_break = True
471 477 del stack[:]
472 478
473 479 def remove(self, group):
474 480 try:
475 481 self.queue[group.depth].remove(group)
476 482 except ValueError:
477 483 pass
478 484
479 485 try:
480 486 _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__)
481 487 except AttributeError: # Python 3
482 488 _baseclass_reprs = (object.__repr__,)
483 489
484 490
485 491 def _default_pprint(obj, p, cycle):
486 492 """
487 493 The default print function. Used if an object does not provide one and
488 494 it's none of the builtin objects.
489 495 """
490 496 klass = _safe_getattr(obj, '__class__', None) or type(obj)
491 497 if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs:
492 498 # A user-provided repr. Find newlines and replace them with p.break_()
493 499 _repr_pprint(obj, p, cycle)
494 500 return
495 501 p.begin_group(1, '<')
496 502 p.pretty(klass)
497 503 p.text(' at 0x%x' % id(obj))
498 504 if cycle:
499 505 p.text(' ...')
500 506 elif p.verbose:
501 507 first = True
502 508 for key in dir(obj):
503 509 if not key.startswith('_'):
504 510 try:
505 511 value = getattr(obj, key)
506 512 except AttributeError:
507 513 continue
508 514 if isinstance(value, types.MethodType):
509 515 continue
510 516 if not first:
511 517 p.text(',')
512 518 p.breakable()
513 519 p.text(key)
514 520 p.text('=')
515 521 step = len(key) + 1
516 522 p.indentation += step
517 523 p.pretty(value)
518 524 p.indentation -= step
519 525 first = False
520 526 p.end_group(1, '>')
521 527
522 528
523 529 def _seq_pprinter_factory(start, end, basetype):
524 530 """
525 531 Factory that returns a pprint function useful for sequences. Used by
526 532 the default pprint for tuples, dicts, and lists.
527 533 """
528 534 def inner(obj, p, cycle):
529 535 typ = type(obj)
530 536 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
531 537 # If the subclass provides its own repr, use it instead.
532 538 return p.text(typ.__repr__(obj))
533 539
534 540 if cycle:
535 541 return p.text(start + '...' + end)
536 542 step = len(start)
537 543 p.begin_group(step, start)
538 544 for idx, x in p._enumerate(obj):
539 545 if idx:
540 546 p.text(',')
541 547 p.breakable()
542 548 p.pretty(x)
543 549 if len(obj) == 1 and type(obj) is tuple:
544 550 # Special case for 1-item tuples.
545 551 p.text(',')
546 552 p.end_group(step, end)
547 553 return inner
548 554
549 555
550 556 def _set_pprinter_factory(start, end, basetype):
551 557 """
552 558 Factory that returns a pprint function useful for sets and frozensets.
553 559 """
554 560 def inner(obj, p, cycle):
555 561 typ = type(obj)
556 562 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
557 563 # If the subclass provides its own repr, use it instead.
558 564 return p.text(typ.__repr__(obj))
559 565
560 566 if cycle:
561 567 return p.text(start + '...' + end)
562 568 if len(obj) == 0:
563 569 # Special case.
564 570 p.text(basetype.__name__ + '()')
565 571 else:
566 572 step = len(start)
567 573 p.begin_group(step, start)
568 574 # Like dictionary keys, we will try to sort the items if there aren't too many
569 575 items = obj
570 576 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
571 577 try:
572 578 items = sorted(obj)
573 579 except Exception:
574 580 # Sometimes the items don't sort.
575 581 pass
576 582 for idx, x in p._enumerate(items):
577 583 if idx:
578 584 p.text(',')
579 585 p.breakable()
580 586 p.pretty(x)
581 587 p.end_group(step, end)
582 588 return inner
583 589
584 590
585 591 def _dict_pprinter_factory(start, end, basetype=None):
586 592 """
587 593 Factory that returns a pprint function used by the default pprint of
588 594 dicts and dict proxies.
589 595 """
590 596 def inner(obj, p, cycle):
591 597 typ = type(obj)
592 598 if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:
593 599 # If the subclass provides its own repr, use it instead.
594 600 return p.text(typ.__repr__(obj))
595 601
596 602 if cycle:
597 603 return p.text('{...}')
598 604 step = len(start)
599 605 p.begin_group(step, start)
600 606 keys = obj.keys()
601 607 # if dict isn't large enough to be truncated, sort keys before displaying
602 608 if not (p.max_seq_length and len(obj) >= p.max_seq_length):
603 609 try:
604 610 keys = sorted(keys)
605 611 except Exception:
606 612 # Sometimes the keys don't sort.
607 613 pass
608 614 for idx, key in p._enumerate(keys):
609 615 if idx:
610 616 p.text(',')
611 617 p.breakable()
612 618 p.pretty(key)
613 619 p.text(': ')
614 620 p.pretty(obj[key])
615 621 p.end_group(step, end)
616 622 return inner
617 623
618 624
619 625 def _super_pprint(obj, p, cycle):
620 626 """The pprint for the super type."""
621 627 p.begin_group(8, '<super: ')
622 628 p.pretty(obj.__thisclass__)
623 629 p.text(',')
624 630 p.breakable()
625 631 if PYPY: # In PyPy, super() objects don't have __self__ attributes
626 632 dself = obj.__repr__.__self__
627 633 p.pretty(None if dself is obj else dself)
628 634 else:
629 635 p.pretty(obj.__self__)
630 636 p.end_group(8, '>')
631 637
632 638
633 639 def _re_pattern_pprint(obj, p, cycle):
634 640 """The pprint function for regular expression patterns."""
635 641 p.text('re.compile(')
636 642 pattern = repr(obj.pattern)
637 643 if pattern[:1] in 'uU':
638 644 pattern = pattern[1:]
639 645 prefix = 'ur'
640 646 else:
641 647 prefix = 'r'
642 648 pattern = prefix + pattern.replace('\\\\', '\\')
643 649 p.text(pattern)
644 650 if obj.flags:
645 651 p.text(',')
646 652 p.breakable()
647 653 done_one = False
648 654 for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
649 655 'UNICODE', 'VERBOSE', 'DEBUG'):
650 656 if obj.flags & getattr(re, flag):
651 657 if done_one:
652 658 p.text('|')
653 659 p.text('re.' + flag)
654 660 done_one = True
655 661 p.text(')')
656 662
657 663
658 664 def _type_pprint(obj, p, cycle):
659 665 """The pprint for classes and types."""
660 666 # Heap allocated types might not have the module attribute,
661 667 # and others may set it to None.
662 668
663 669 # Checks for a __repr__ override in the metaclass. Can't compare the
664 670 # type(obj).__repr__ directly because in PyPy the representation function
665 671 # inherited from type isn't the same type.__repr__
666 672 if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
667 673 _repr_pprint(obj, p, cycle)
668 674 return
669 675
670 676 mod = _safe_getattr(obj, '__module__', None)
671 677 try:
672 678 name = obj.__qualname__
673 679 if not isinstance(name, str):
674 680 # This can happen if the type implements __qualname__ as a property
675 681 # or other descriptor in Python 2.
676 682 raise Exception("Try __name__")
677 683 except Exception:
678 684 name = obj.__name__
679 685 if not isinstance(name, str):
680 686 name = '<unknown type>'
681 687
682 688 if mod in (None, '__builtin__', 'builtins', 'exceptions'):
683 689 p.text(name)
684 690 else:
685 691 p.text(mod + '.' + name)
686 692
687 693
688 694 def _repr_pprint(obj, p, cycle):
689 695 """A pprint that just redirects to the normal repr function."""
690 696 # Find newlines and replace them with p.break_()
691 697 output = repr(obj)
692 698 for idx,output_line in enumerate(output.splitlines()):
693 699 if idx:
694 700 p.break_()
695 701 p.text(output_line)
696 702
697 703
698 704 def _function_pprint(obj, p, cycle):
699 705 """Base pprint for all functions and builtin functions."""
700 706 name = _safe_getattr(obj, '__qualname__', obj.__name__)
701 707 mod = obj.__module__
702 708 if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
703 709 name = mod + '.' + name
704 710 p.text('<function %s>' % name)
705 711
706 712
707 713 def _exception_pprint(obj, p, cycle):
708 714 """Base pprint for all exceptions."""
709 715 name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
710 716 if obj.__class__.__module__ not in ('exceptions', 'builtins'):
711 717 name = '%s.%s' % (obj.__class__.__module__, name)
712 718 step = len(name) + 1
713 719 p.begin_group(step, name + '(')
714 720 for idx, arg in enumerate(getattr(obj, 'args', ())):
715 721 if idx:
716 722 p.text(',')
717 723 p.breakable()
718 724 p.pretty(arg)
719 725 p.end_group(step, ')')
720 726
721 727
722 728 #: the exception base
723 729 try:
724 730 _exception_base = BaseException
725 731 except NameError:
726 732 _exception_base = Exception
727 733
728 734
729 735 #: printers for builtin types
730 736 _type_pprinters = {
731 737 int: _repr_pprint,
732 738 float: _repr_pprint,
733 739 str: _repr_pprint,
734 740 tuple: _seq_pprinter_factory('(', ')', tuple),
735 741 list: _seq_pprinter_factory('[', ']', list),
736 742 dict: _dict_pprinter_factory('{', '}', dict),
737 743
738 744 set: _set_pprinter_factory('{', '}', set),
739 745 frozenset: _set_pprinter_factory('frozenset({', '})', frozenset),
740 746 super: _super_pprint,
741 747 _re_pattern_type: _re_pattern_pprint,
742 748 type: _type_pprint,
743 749 types.FunctionType: _function_pprint,
744 750 types.BuiltinFunctionType: _function_pprint,
745 751 types.MethodType: _repr_pprint,
746 752
747 753 datetime.datetime: _repr_pprint,
748 754 datetime.timedelta: _repr_pprint,
749 755 _exception_base: _exception_pprint
750 756 }
751 757
752 758 try:
753 759 # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
754 760 # using dict.setdefault avoids overwritting the dict printer
755 761 _type_pprinters.setdefault(types.DictProxyType,
756 762 _dict_pprinter_factory('dict_proxy({', '})'))
757 763 _type_pprinters[types.ClassType] = _type_pprint
758 764 _type_pprinters[types.SliceType] = _repr_pprint
759 765 except AttributeError: # Python 3
760 766 _type_pprinters[types.MappingProxyType] = \
761 767 _dict_pprinter_factory('mappingproxy({', '})')
762 768 _type_pprinters[slice] = _repr_pprint
763 769
764 770 try:
765 771 _type_pprinters[long] = _repr_pprint
766 772 _type_pprinters[unicode] = _repr_pprint
767 773 except NameError:
768 774 _type_pprinters[range] = _repr_pprint
769 775 _type_pprinters[bytes] = _repr_pprint
770 776
771 777 #: printers for types specified by name
772 778 _deferred_type_pprinters = {
773 779 }
774 780
775 781 def for_type(typ, func):
776 782 """
777 783 Add a pretty printer for a given type.
778 784 """
779 785 oldfunc = _type_pprinters.get(typ, None)
780 786 if func is not None:
781 787 # To support easy restoration of old pprinters, we need to ignore Nones.
782 788 _type_pprinters[typ] = func
783 789 return oldfunc
784 790
785 791 def for_type_by_name(type_module, type_name, func):
786 792 """
787 793 Add a pretty printer for a type specified by the module and name of a type
788 794 rather than the type object itself.
789 795 """
790 796 key = (type_module, type_name)
791 797 oldfunc = _deferred_type_pprinters.get(key, None)
792 798 if func is not None:
793 799 # To support easy restoration of old pprinters, we need to ignore Nones.
794 800 _deferred_type_pprinters[key] = func
795 801 return oldfunc
796 802
797 803
798 804 #: printers for the default singletons
799 805 _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
800 806 NotImplemented]), _repr_pprint)
801 807
802 808
803 809 def _defaultdict_pprint(obj, p, cycle):
804 810 name = obj.__class__.__name__
805 811 with p.group(len(name) + 1, name + '(', ')'):
806 812 if cycle:
807 813 p.text('...')
808 814 else:
809 815 p.pretty(obj.default_factory)
810 816 p.text(',')
811 817 p.breakable()
812 818 p.pretty(dict(obj))
813 819
814 820 def _ordereddict_pprint(obj, p, cycle):
815 821 name = obj.__class__.__name__
816 822 with p.group(len(name) + 1, name + '(', ')'):
817 823 if cycle:
818 824 p.text('...')
819 825 elif len(obj):
820 826 p.pretty(list(obj.items()))
821 827
822 828 def _deque_pprint(obj, p, cycle):
823 829 name = obj.__class__.__name__
824 830 with p.group(len(name) + 1, name + '(', ')'):
825 831 if cycle:
826 832 p.text('...')
827 833 else:
828 834 p.pretty(list(obj))
829 835
830 836
831 837 def _counter_pprint(obj, p, cycle):
832 838 name = obj.__class__.__name__
833 839 with p.group(len(name) + 1, name + '(', ')'):
834 840 if cycle:
835 841 p.text('...')
836 842 elif len(obj):
837 843 p.pretty(dict(obj))
838 844
839 845 for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
840 846 for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
841 847 for_type_by_name('collections', 'deque', _deque_pprint)
842 848 for_type_by_name('collections', 'Counter', _counter_pprint)
843 849
844 850 if __name__ == '__main__':
845 851 from random import randrange
846 852 class Foo(object):
847 853 def __init__(self):
848 854 self.foo = 1
849 855 self.bar = re.compile(r'\s+')
850 856 self.blub = dict.fromkeys(range(30), randrange(1, 40))
851 857 self.hehe = 23424.234234
852 858 self.list = ["blub", "blah", self]
853 859
854 860 def get_foo(self):
855 861 print("foo")
856 862
857 863 pprint(Foo(), verbose=True)
General Comments 0
You need to be logged in to leave comments. Login now