pretty.py 28 KB

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