pretty.py 28 KB

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