pretty.py 30 KB

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