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