pretty.py 28 KB

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