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