pretty.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. import builtins
  2. import collections
  3. import dataclasses
  4. import inspect
  5. import os
  6. import reprlib
  7. import sys
  8. from array import array
  9. from collections import Counter, UserDict, UserList, defaultdict, deque
  10. from dataclasses import dataclass, fields, is_dataclass
  11. from inspect import isclass
  12. from itertools import islice
  13. from types import MappingProxyType
  14. from typing import (
  15. TYPE_CHECKING,
  16. Any,
  17. Callable,
  18. DefaultDict,
  19. Deque,
  20. Dict,
  21. Iterable,
  22. List,
  23. Optional,
  24. Sequence,
  25. Set,
  26. Tuple,
  27. Union,
  28. )
  29. from rich.repr import RichReprResult
  30. try:
  31. import attr as _attr_module
  32. _has_attrs = hasattr(_attr_module, "ib")
  33. except ImportError: # pragma: no cover
  34. _has_attrs = False
  35. from . import get_console
  36. from ._loop import loop_last
  37. from ._pick import pick_bool
  38. from .abc import RichRenderable
  39. from .cells import cell_len
  40. from .highlighter import ReprHighlighter
  41. from .jupyter import JupyterMixin, JupyterRenderable
  42. from .measure import Measurement
  43. from .text import Text
  44. if TYPE_CHECKING:
  45. from .console import (
  46. Console,
  47. ConsoleOptions,
  48. HighlighterType,
  49. JustifyMethod,
  50. OverflowMethod,
  51. RenderResult,
  52. )
  53. def _is_attr_object(obj: Any) -> bool:
  54. """Check if an object was created with attrs module."""
  55. return _has_attrs and _attr_module.has(type(obj))
  56. def _get_attr_fields(obj: Any) -> Sequence["_attr_module.Attribute[Any]"]:
  57. """Get fields for an attrs object."""
  58. return _attr_module.fields(type(obj)) if _has_attrs else []
  59. def _is_dataclass_repr(obj: object) -> bool:
  60. """Check if an instance of a dataclass contains the default repr.
  61. Args:
  62. obj (object): A dataclass instance.
  63. Returns:
  64. bool: True if the default repr is used, False if there is a custom repr.
  65. """
  66. # Digging in to a lot of internals here
  67. # Catching all exceptions in case something is missing on a non CPython implementation
  68. try:
  69. return obj.__repr__.__code__.co_filename in (
  70. dataclasses.__file__,
  71. reprlib.__file__,
  72. )
  73. except Exception: # pragma: no coverage
  74. return False
  75. _dummy_namedtuple = collections.namedtuple("_dummy_namedtuple", [])
  76. def _has_default_namedtuple_repr(obj: object) -> bool:
  77. """Check if an instance of namedtuple contains the default repr
  78. Args:
  79. obj (object): A namedtuple
  80. Returns:
  81. bool: True if the default repr is used, False if there's a custom repr.
  82. """
  83. obj_file = None
  84. try:
  85. obj_file = inspect.getfile(obj.__repr__)
  86. except (OSError, TypeError):
  87. # OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available.
  88. # TypeError trapped defensively, in case of object without filename slips through.
  89. pass
  90. default_repr_file = inspect.getfile(_dummy_namedtuple.__repr__)
  91. return obj_file == default_repr_file
  92. def _ipy_display_hook(
  93. value: Any,
  94. console: Optional["Console"] = None,
  95. overflow: "OverflowMethod" = "ignore",
  96. crop: bool = False,
  97. indent_guides: bool = False,
  98. max_length: Optional[int] = None,
  99. max_string: Optional[int] = None,
  100. max_depth: Optional[int] = None,
  101. expand_all: bool = False,
  102. ) -> Union[str, None]:
  103. # needed here to prevent circular import:
  104. from .console import ConsoleRenderable
  105. # always skip rich generated jupyter renderables or None values
  106. if _safe_isinstance(value, JupyterRenderable) or value is None:
  107. return None
  108. console = console or get_console()
  109. with console.capture() as capture:
  110. # certain renderables should start on a new line
  111. if _safe_isinstance(value, ConsoleRenderable):
  112. console.line()
  113. console.print(
  114. (
  115. value
  116. if _safe_isinstance(value, RichRenderable)
  117. else Pretty(
  118. value,
  119. overflow=overflow,
  120. indent_guides=indent_guides,
  121. max_length=max_length,
  122. max_string=max_string,
  123. max_depth=max_depth,
  124. expand_all=expand_all,
  125. margin=12,
  126. )
  127. ),
  128. crop=crop,
  129. new_line_start=True,
  130. end="",
  131. )
  132. # strip trailing newline, not usually part of a text repr
  133. # I'm not sure if this should be prevented at a lower level
  134. return capture.get().rstrip("\n")
  135. def _safe_isinstance(
  136. obj: object, class_or_tuple: Union[type, Tuple[type, ...]]
  137. ) -> bool:
  138. """isinstance can fail in rare cases, for example types with no __class__"""
  139. try:
  140. return isinstance(obj, class_or_tuple)
  141. except Exception:
  142. return False
  143. def install(
  144. console: Optional["Console"] = None,
  145. overflow: "OverflowMethod" = "ignore",
  146. crop: bool = False,
  147. indent_guides: bool = False,
  148. max_length: Optional[int] = None,
  149. max_string: Optional[int] = None,
  150. max_depth: Optional[int] = None,
  151. expand_all: bool = False,
  152. ) -> None:
  153. """Install automatic pretty printing in the Python REPL.
  154. Args:
  155. console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
  156. overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore".
  157. crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.
  158. indent_guides (bool, optional): Enable indentation guides. Defaults to False.
  159. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  160. Defaults to None.
  161. max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
  162. max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
  163. expand_all (bool, optional): Expand all containers. Defaults to False.
  164. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  165. """
  166. from rich import get_console
  167. console = console or get_console()
  168. assert console is not None
  169. def display_hook(value: Any) -> None:
  170. """Replacement sys.displayhook which prettifies objects with Rich."""
  171. if value is not None:
  172. assert console is not None
  173. builtins._ = None # type: ignore[attr-defined]
  174. console.print(
  175. (
  176. value
  177. if _safe_isinstance(value, RichRenderable)
  178. else Pretty(
  179. value,
  180. overflow=overflow,
  181. indent_guides=indent_guides,
  182. max_length=max_length,
  183. max_string=max_string,
  184. max_depth=max_depth,
  185. expand_all=expand_all,
  186. )
  187. ),
  188. crop=crop,
  189. )
  190. builtins._ = value # type: ignore[attr-defined]
  191. try:
  192. ip = get_ipython() # type: ignore[name-defined]
  193. except NameError:
  194. sys.displayhook = display_hook
  195. else:
  196. from IPython.core.formatters import BaseFormatter
  197. class RichFormatter(BaseFormatter): # type: ignore[misc]
  198. pprint: bool = True
  199. def __call__(self, value: Any) -> Any:
  200. if self.pprint:
  201. return _ipy_display_hook(
  202. value,
  203. console=get_console(),
  204. overflow=overflow,
  205. indent_guides=indent_guides,
  206. max_length=max_length,
  207. max_string=max_string,
  208. max_depth=max_depth,
  209. expand_all=expand_all,
  210. )
  211. else:
  212. return repr(value)
  213. # replace plain text formatter with rich formatter
  214. rich_formatter = RichFormatter()
  215. ip.display_formatter.formatters["text/plain"] = rich_formatter
  216. class Pretty(JupyterMixin):
  217. """A rich renderable that pretty prints an object.
  218. Args:
  219. _object (Any): An object to pretty print.
  220. highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
  221. indent_size (int, optional): Number of spaces in indent. Defaults to 4.
  222. justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
  223. overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
  224. no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
  225. indent_guides (bool, optional): Enable indentation guides. Defaults to False.
  226. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  227. Defaults to None.
  228. max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
  229. max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
  230. expand_all (bool, optional): Expand all containers. Defaults to False.
  231. margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.
  232. insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.
  233. """
  234. def __init__(
  235. self,
  236. _object: Any,
  237. highlighter: Optional["HighlighterType"] = None,
  238. *,
  239. indent_size: int = 4,
  240. justify: Optional["JustifyMethod"] = None,
  241. overflow: Optional["OverflowMethod"] = None,
  242. no_wrap: Optional[bool] = False,
  243. indent_guides: bool = False,
  244. max_length: Optional[int] = None,
  245. max_string: Optional[int] = None,
  246. max_depth: Optional[int] = None,
  247. expand_all: bool = False,
  248. margin: int = 0,
  249. insert_line: bool = False,
  250. ) -> None:
  251. self._object = _object
  252. self.highlighter = highlighter or ReprHighlighter()
  253. self.indent_size = indent_size
  254. self.justify: Optional["JustifyMethod"] = justify
  255. self.overflow: Optional["OverflowMethod"] = overflow
  256. self.no_wrap = no_wrap
  257. self.indent_guides = indent_guides
  258. self.max_length = max_length
  259. self.max_string = max_string
  260. self.max_depth = max_depth
  261. self.expand_all = expand_all
  262. self.margin = margin
  263. self.insert_line = insert_line
  264. def __rich_console__(
  265. self, console: "Console", options: "ConsoleOptions"
  266. ) -> "RenderResult":
  267. pretty_str = pretty_repr(
  268. self._object,
  269. max_width=options.max_width - self.margin,
  270. indent_size=self.indent_size,
  271. max_length=self.max_length,
  272. max_string=self.max_string,
  273. max_depth=self.max_depth,
  274. expand_all=self.expand_all,
  275. )
  276. pretty_text = Text.from_ansi(
  277. pretty_str,
  278. justify=self.justify or options.justify,
  279. overflow=self.overflow or options.overflow,
  280. no_wrap=pick_bool(self.no_wrap, options.no_wrap),
  281. style="pretty",
  282. )
  283. pretty_text = (
  284. self.highlighter(pretty_text)
  285. if pretty_text
  286. else Text(
  287. f"{type(self._object)}.__repr__ returned empty string",
  288. style="dim italic",
  289. )
  290. )
  291. if self.indent_guides and not options.ascii_only:
  292. pretty_text = pretty_text.with_indent_guides(
  293. self.indent_size, style="repr.indent"
  294. )
  295. if self.insert_line and "\n" in pretty_text:
  296. yield ""
  297. yield pretty_text
  298. def __rich_measure__(
  299. self, console: "Console", options: "ConsoleOptions"
  300. ) -> "Measurement":
  301. pretty_str = pretty_repr(
  302. self._object,
  303. max_width=options.max_width,
  304. indent_size=self.indent_size,
  305. max_length=self.max_length,
  306. max_string=self.max_string,
  307. max_depth=self.max_depth,
  308. expand_all=self.expand_all,
  309. )
  310. text_width = (
  311. max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0
  312. )
  313. return Measurement(text_width, text_width)
  314. def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:
  315. return (
  316. f"defaultdict({_object.default_factory!r}, {{",
  317. "})",
  318. f"defaultdict({_object.default_factory!r}, {{}})",
  319. )
  320. def _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]:
  321. if _object.maxlen is None:
  322. return ("deque([", "])", "deque()")
  323. return (
  324. "deque([",
  325. f"], maxlen={_object.maxlen})",
  326. f"deque(maxlen={_object.maxlen})",
  327. )
  328. def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]:
  329. return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})")
  330. _BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {
  331. os._Environ: lambda _object: ("environ({", "})", "environ({})"),
  332. array: _get_braces_for_array,
  333. defaultdict: _get_braces_for_defaultdict,
  334. Counter: lambda _object: ("Counter({", "})", "Counter()"),
  335. deque: _get_braces_for_deque,
  336. dict: lambda _object: ("{", "}", "{}"),
  337. UserDict: lambda _object: ("{", "}", "{}"),
  338. frozenset: lambda _object: ("frozenset({", "})", "frozenset()"),
  339. list: lambda _object: ("[", "]", "[]"),
  340. UserList: lambda _object: ("[", "]", "[]"),
  341. set: lambda _object: ("{", "}", "set()"),
  342. tuple: lambda _object: ("(", ")", "()"),
  343. MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"),
  344. }
  345. _CONTAINERS = tuple(_BRACES.keys())
  346. _MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)
  347. def is_expandable(obj: Any) -> bool:
  348. """Check if an object may be expanded by pretty print."""
  349. return (
  350. _safe_isinstance(obj, _CONTAINERS)
  351. or (is_dataclass(obj))
  352. or (hasattr(obj, "__rich_repr__"))
  353. or _is_attr_object(obj)
  354. ) and not isclass(obj)
  355. @dataclass
  356. class Node:
  357. """A node in a repr tree. May be atomic or a container."""
  358. key_repr: str = ""
  359. value_repr: str = ""
  360. open_brace: str = ""
  361. close_brace: str = ""
  362. empty: str = ""
  363. last: bool = False
  364. is_tuple: bool = False
  365. is_namedtuple: bool = False
  366. children: Optional[List["Node"]] = None
  367. key_separator: str = ": "
  368. separator: str = ", "
  369. def iter_tokens(self) -> Iterable[str]:
  370. """Generate tokens for this node."""
  371. if self.key_repr:
  372. yield self.key_repr
  373. yield self.key_separator
  374. if self.value_repr:
  375. yield self.value_repr
  376. elif self.children is not None:
  377. if self.children:
  378. yield self.open_brace
  379. if self.is_tuple and not self.is_namedtuple and len(self.children) == 1:
  380. yield from self.children[0].iter_tokens()
  381. yield ","
  382. else:
  383. for child in self.children:
  384. yield from child.iter_tokens()
  385. if not child.last:
  386. yield self.separator
  387. yield self.close_brace
  388. else:
  389. yield self.empty
  390. def check_length(self, start_length: int, max_length: int) -> bool:
  391. """Check the length fits within a limit.
  392. Args:
  393. start_length (int): Starting length of the line (indent, prefix, suffix).
  394. max_length (int): Maximum length.
  395. Returns:
  396. bool: True if the node can be rendered within max length, otherwise False.
  397. """
  398. total_length = start_length
  399. for token in self.iter_tokens():
  400. total_length += cell_len(token)
  401. if total_length > max_length:
  402. return False
  403. return True
  404. def __str__(self) -> str:
  405. repr_text = "".join(self.iter_tokens())
  406. return repr_text
  407. def render(
  408. self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False
  409. ) -> str:
  410. """Render the node to a pretty repr.
  411. Args:
  412. max_width (int, optional): Maximum width of the repr. Defaults to 80.
  413. indent_size (int, optional): Size of indents. Defaults to 4.
  414. expand_all (bool, optional): Expand all levels. Defaults to False.
  415. Returns:
  416. str: A repr string of the original object.
  417. """
  418. lines = [_Line(node=self, is_root=True)]
  419. line_no = 0
  420. while line_no < len(lines):
  421. line = lines[line_no]
  422. if line.expandable and not line.expanded:
  423. if expand_all or not line.check_length(max_width):
  424. lines[line_no : line_no + 1] = line.expand(indent_size)
  425. line_no += 1
  426. repr_str = "\n".join(str(line) for line in lines)
  427. return repr_str
  428. @dataclass
  429. class _Line:
  430. """A line in repr output."""
  431. parent: Optional["_Line"] = None
  432. is_root: bool = False
  433. node: Optional[Node] = None
  434. text: str = ""
  435. suffix: str = ""
  436. whitespace: str = ""
  437. expanded: bool = False
  438. last: bool = False
  439. @property
  440. def expandable(self) -> bool:
  441. """Check if the line may be expanded."""
  442. return bool(self.node is not None and self.node.children)
  443. def check_length(self, max_length: int) -> bool:
  444. """Check this line fits within a given number of cells."""
  445. start_length = (
  446. len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix)
  447. )
  448. assert self.node is not None
  449. return self.node.check_length(start_length, max_length)
  450. def expand(self, indent_size: int) -> Iterable["_Line"]:
  451. """Expand this line by adding children on their own line."""
  452. node = self.node
  453. assert node is not None
  454. whitespace = self.whitespace
  455. assert node.children
  456. if node.key_repr:
  457. new_line = yield _Line(
  458. text=f"{node.key_repr}{node.key_separator}{node.open_brace}",
  459. whitespace=whitespace,
  460. )
  461. else:
  462. new_line = yield _Line(text=node.open_brace, whitespace=whitespace)
  463. child_whitespace = self.whitespace + " " * indent_size
  464. tuple_of_one = node.is_tuple and len(node.children) == 1
  465. for last, child in loop_last(node.children):
  466. separator = "," if tuple_of_one else node.separator
  467. line = _Line(
  468. parent=new_line,
  469. node=child,
  470. whitespace=child_whitespace,
  471. suffix=separator,
  472. last=last and not tuple_of_one,
  473. )
  474. yield line
  475. yield _Line(
  476. text=node.close_brace,
  477. whitespace=whitespace,
  478. suffix=self.suffix,
  479. last=self.last,
  480. )
  481. def __str__(self) -> str:
  482. if self.last:
  483. return f"{self.whitespace}{self.text}{self.node or ''}"
  484. else:
  485. return (
  486. f"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}"
  487. )
  488. def _is_namedtuple(obj: Any) -> bool:
  489. """Checks if an object is most likely a namedtuple. It is possible
  490. to craft an object that passes this check and isn't a namedtuple, but
  491. there is only a minuscule chance of this happening unintentionally.
  492. Args:
  493. obj (Any): The object to test
  494. Returns:
  495. bool: True if the object is a namedtuple. False otherwise.
  496. """
  497. try:
  498. fields = getattr(obj, "_fields", None)
  499. except Exception:
  500. # Being very defensive - if we cannot get the attr then its not a namedtuple
  501. return False
  502. return isinstance(obj, tuple) and isinstance(fields, tuple)
  503. def traverse(
  504. _object: Any,
  505. max_length: Optional[int] = None,
  506. max_string: Optional[int] = None,
  507. max_depth: Optional[int] = None,
  508. ) -> Node:
  509. """Traverse object and generate a tree.
  510. Args:
  511. _object (Any): Object to be traversed.
  512. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  513. Defaults to None.
  514. max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
  515. Defaults to None.
  516. max_depth (int, optional): Maximum depth of data structures, or None for no maximum.
  517. Defaults to None.
  518. Returns:
  519. Node: The root of a tree structure which can be used to render a pretty repr.
  520. """
  521. def to_repr(obj: Any) -> str:
  522. """Get repr string for an object, but catch errors."""
  523. if (
  524. max_string is not None
  525. and _safe_isinstance(obj, (bytes, str))
  526. and len(obj) > max_string
  527. ):
  528. truncated = len(obj) - max_string
  529. obj_repr = f"{obj[:max_string]!r}+{truncated}"
  530. else:
  531. try:
  532. obj_repr = repr(obj)
  533. except Exception as error:
  534. obj_repr = f"<repr-error {str(error)!r}>"
  535. return obj_repr
  536. visited_ids: Set[int] = set()
  537. push_visited = visited_ids.add
  538. pop_visited = visited_ids.remove
  539. def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:
  540. """Walk the object depth first."""
  541. obj_id = id(obj)
  542. if obj_id in visited_ids:
  543. # Recursion detected
  544. return Node(value_repr="...")
  545. obj_type = type(obj)
  546. children: List[Node]
  547. reached_max_depth = max_depth is not None and depth >= max_depth
  548. def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:
  549. for arg in rich_args:
  550. if _safe_isinstance(arg, tuple):
  551. if len(arg) == 3:
  552. key, child, default = arg
  553. if default == child:
  554. continue
  555. yield key, child
  556. elif len(arg) == 2:
  557. key, child = arg
  558. yield key, child
  559. elif len(arg) == 1:
  560. yield arg[0]
  561. else:
  562. yield arg
  563. try:
  564. fake_attributes = hasattr(
  565. obj, "awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492"
  566. )
  567. except Exception:
  568. fake_attributes = False
  569. rich_repr_result: Optional[RichReprResult] = None
  570. if not fake_attributes:
  571. try:
  572. if hasattr(obj, "__rich_repr__") and not isclass(obj):
  573. rich_repr_result = obj.__rich_repr__()
  574. except Exception:
  575. pass
  576. if rich_repr_result is not None:
  577. push_visited(obj_id)
  578. angular = getattr(obj.__rich_repr__, "angular", False)
  579. args = list(iter_rich_args(rich_repr_result))
  580. class_name = obj.__class__.__name__
  581. if args:
  582. children = []
  583. append = children.append
  584. if reached_max_depth:
  585. if angular:
  586. node = Node(value_repr=f"<{class_name}...>")
  587. else:
  588. node = Node(value_repr=f"{class_name}(...)")
  589. else:
  590. if angular:
  591. node = Node(
  592. open_brace=f"<{class_name} ",
  593. close_brace=">",
  594. children=children,
  595. last=root,
  596. separator=" ",
  597. )
  598. else:
  599. node = Node(
  600. open_brace=f"{class_name}(",
  601. close_brace=")",
  602. children=children,
  603. last=root,
  604. )
  605. for last, arg in loop_last(args):
  606. if _safe_isinstance(arg, tuple):
  607. key, child = arg
  608. child_node = _traverse(child, depth=depth + 1)
  609. child_node.last = last
  610. child_node.key_repr = key
  611. child_node.key_separator = "="
  612. append(child_node)
  613. else:
  614. child_node = _traverse(arg, depth=depth + 1)
  615. child_node.last = last
  616. append(child_node)
  617. else:
  618. node = Node(
  619. value_repr=f"<{class_name}>" if angular else f"{class_name}()",
  620. children=[],
  621. last=root,
  622. )
  623. pop_visited(obj_id)
  624. elif _is_attr_object(obj) and not fake_attributes:
  625. push_visited(obj_id)
  626. children = []
  627. append = children.append
  628. attr_fields = _get_attr_fields(obj)
  629. if attr_fields:
  630. if reached_max_depth:
  631. node = Node(value_repr=f"{obj.__class__.__name__}(...)")
  632. else:
  633. node = Node(
  634. open_brace=f"{obj.__class__.__name__}(",
  635. close_brace=")",
  636. children=children,
  637. last=root,
  638. )
  639. def iter_attrs() -> (
  640. Iterable[Tuple[str, Any, Optional[Callable[[Any], str]]]]
  641. ):
  642. """Iterate over attr fields and values."""
  643. for attr in attr_fields:
  644. if attr.repr:
  645. try:
  646. value = getattr(obj, attr.name)
  647. except Exception as error:
  648. # Can happen, albeit rarely
  649. yield (attr.name, error, None)
  650. else:
  651. yield (
  652. attr.name,
  653. value,
  654. attr.repr if callable(attr.repr) else None,
  655. )
  656. for last, (name, value, repr_callable) in loop_last(iter_attrs()):
  657. if repr_callable:
  658. child_node = Node(value_repr=str(repr_callable(value)))
  659. else:
  660. child_node = _traverse(value, depth=depth + 1)
  661. child_node.last = last
  662. child_node.key_repr = name
  663. child_node.key_separator = "="
  664. append(child_node)
  665. else:
  666. node = Node(
  667. value_repr=f"{obj.__class__.__name__}()", children=[], last=root
  668. )
  669. pop_visited(obj_id)
  670. elif (
  671. is_dataclass(obj)
  672. and not _safe_isinstance(obj, type)
  673. and not fake_attributes
  674. and _is_dataclass_repr(obj)
  675. ):
  676. push_visited(obj_id)
  677. children = []
  678. append = children.append
  679. if reached_max_depth:
  680. node = Node(value_repr=f"{obj.__class__.__name__}(...)")
  681. else:
  682. node = Node(
  683. open_brace=f"{obj.__class__.__name__}(",
  684. close_brace=")",
  685. children=children,
  686. last=root,
  687. empty=f"{obj.__class__.__name__}()",
  688. )
  689. for last, field in loop_last(
  690. field
  691. for field in fields(obj)
  692. if field.repr and hasattr(obj, field.name)
  693. ):
  694. child_node = _traverse(getattr(obj, field.name), depth=depth + 1)
  695. child_node.key_repr = field.name
  696. child_node.last = last
  697. child_node.key_separator = "="
  698. append(child_node)
  699. pop_visited(obj_id)
  700. elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj):
  701. push_visited(obj_id)
  702. class_name = obj.__class__.__name__
  703. if reached_max_depth:
  704. # If we've reached the max depth, we still show the class name, but not its contents
  705. node = Node(
  706. value_repr=f"{class_name}(...)",
  707. )
  708. else:
  709. children = []
  710. append = children.append
  711. node = Node(
  712. open_brace=f"{class_name}(",
  713. close_brace=")",
  714. children=children,
  715. empty=f"{class_name}()",
  716. )
  717. for last, (key, value) in loop_last(obj._asdict().items()):
  718. child_node = _traverse(value, depth=depth + 1)
  719. child_node.key_repr = key
  720. child_node.last = last
  721. child_node.key_separator = "="
  722. append(child_node)
  723. pop_visited(obj_id)
  724. elif _safe_isinstance(obj, _CONTAINERS):
  725. for container_type in _CONTAINERS:
  726. if _safe_isinstance(obj, container_type):
  727. obj_type = container_type
  728. break
  729. push_visited(obj_id)
  730. open_brace, close_brace, empty = _BRACES[obj_type](obj)
  731. if reached_max_depth:
  732. node = Node(value_repr=f"{open_brace}...{close_brace}")
  733. elif obj_type.__repr__ != type(obj).__repr__:
  734. node = Node(value_repr=to_repr(obj), last=root)
  735. elif obj:
  736. children = []
  737. node = Node(
  738. open_brace=open_brace,
  739. close_brace=close_brace,
  740. children=children,
  741. last=root,
  742. )
  743. append = children.append
  744. num_items = len(obj)
  745. last_item_index = num_items - 1
  746. if _safe_isinstance(obj, _MAPPING_CONTAINERS):
  747. iter_items = iter(obj.items())
  748. if max_length is not None:
  749. iter_items = islice(iter_items, max_length)
  750. for index, (key, child) in enumerate(iter_items):
  751. child_node = _traverse(child, depth=depth + 1)
  752. child_node.key_repr = to_repr(key)
  753. child_node.last = index == last_item_index
  754. append(child_node)
  755. else:
  756. iter_values = iter(obj)
  757. if max_length is not None:
  758. iter_values = islice(iter_values, max_length)
  759. for index, child in enumerate(iter_values):
  760. child_node = _traverse(child, depth=depth + 1)
  761. child_node.last = index == last_item_index
  762. append(child_node)
  763. if max_length is not None and num_items > max_length:
  764. append(Node(value_repr=f"... +{num_items - max_length}", last=True))
  765. else:
  766. node = Node(empty=empty, children=[], last=root)
  767. pop_visited(obj_id)
  768. else:
  769. node = Node(value_repr=to_repr(obj), last=root)
  770. node.is_tuple = type(obj) == tuple
  771. node.is_namedtuple = _is_namedtuple(obj)
  772. return node
  773. node = _traverse(_object, root=True)
  774. return node
  775. def pretty_repr(
  776. _object: Any,
  777. *,
  778. max_width: int = 80,
  779. indent_size: int = 4,
  780. max_length: Optional[int] = None,
  781. max_string: Optional[int] = None,
  782. max_depth: Optional[int] = None,
  783. expand_all: bool = False,
  784. ) -> str:
  785. """Prettify repr string by expanding on to new lines to fit within a given width.
  786. Args:
  787. _object (Any): Object to repr.
  788. max_width (int, optional): Desired maximum width of repr string. Defaults to 80.
  789. indent_size (int, optional): Number of spaces to indent. Defaults to 4.
  790. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  791. Defaults to None.
  792. max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
  793. Defaults to None.
  794. max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.
  795. Defaults to None.
  796. expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.
  797. Returns:
  798. str: A possibly multi-line representation of the object.
  799. """
  800. if _safe_isinstance(_object, Node):
  801. node = _object
  802. else:
  803. node = traverse(
  804. _object, max_length=max_length, max_string=max_string, max_depth=max_depth
  805. )
  806. repr_str: str = node.render(
  807. max_width=max_width, indent_size=indent_size, expand_all=expand_all
  808. )
  809. return repr_str
  810. def pprint(
  811. _object: Any,
  812. *,
  813. console: Optional["Console"] = None,
  814. indent_guides: bool = True,
  815. max_length: Optional[int] = None,
  816. max_string: Optional[int] = None,
  817. max_depth: Optional[int] = None,
  818. expand_all: bool = False,
  819. ) -> None:
  820. """A convenience function for pretty printing.
  821. Args:
  822. _object (Any): Object to pretty print.
  823. console (Console, optional): Console instance, or None to use default. Defaults to None.
  824. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  825. Defaults to None.
  826. max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.
  827. max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.
  828. indent_guides (bool, optional): Enable indentation guides. Defaults to True.
  829. expand_all (bool, optional): Expand all containers. Defaults to False.
  830. """
  831. _console = get_console() if console is None else console
  832. _console.print(
  833. Pretty(
  834. _object,
  835. max_length=max_length,
  836. max_string=max_string,
  837. max_depth=max_depth,
  838. indent_guides=indent_guides,
  839. expand_all=expand_all,
  840. overflow="ignore",
  841. ),
  842. soft_wrap=True,
  843. )
  844. if __name__ == "__main__": # pragma: no cover
  845. class BrokenRepr:
  846. def __repr__(self) -> str:
  847. 1 / 0
  848. return "this will fail"
  849. from typing import NamedTuple
  850. class StockKeepingUnit(NamedTuple):
  851. name: str
  852. description: str
  853. price: float
  854. category: str
  855. reviews: List[str]
  856. d = defaultdict(int)
  857. d["foo"] = 5
  858. data = {
  859. "foo": [
  860. 1,
  861. "Hello World!",
  862. 100.123,
  863. 323.232,
  864. 432324.0,
  865. {5, 6, 7, (1, 2, 3, 4), 8},
  866. ],
  867. "bar": frozenset({1, 2, 3}),
  868. "defaultdict": defaultdict(
  869. list, {"crumble": ["apple", "rhubarb", "butter", "sugar", "flour"]}
  870. ),
  871. "counter": Counter(
  872. [
  873. "apple",
  874. "orange",
  875. "pear",
  876. "kumquat",
  877. "kumquat",
  878. "durian" * 100,
  879. ]
  880. ),
  881. "atomic": (False, True, None),
  882. "namedtuple": StockKeepingUnit(
  883. "Sparkling British Spring Water",
  884. "Carbonated spring water",
  885. 0.9,
  886. "water",
  887. ["its amazing!", "its terrible!"],
  888. ),
  889. "Broken": BrokenRepr(),
  890. }
  891. data["foo"].append(data) # type: ignore[attr-defined]
  892. from rich import print
  893. print(Pretty(data, indent_guides=True, max_string=20))
  894. class Thing:
  895. def __repr__(self) -> str:
  896. return "Hello\x1b[38;5;239m World!"
  897. print(Pretty(Thing()))