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