pretty.py 28 KB

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