pretty.py 30 KB

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