8from collections
import Counter, UserDict, UserList, defaultdict, deque
9from dataclasses
import dataclass, fields, is_dataclass
10from inspect
import isclass
11from itertools
import islice
12from types
import MappingProxyType
31 import attr
as _attr_module
37from .
import get_console
38from ._loop
import loop_last
39from ._pick
import pick_bool
40from .abc
import RichRenderable
41from .cells
import cell_len
42from .highlighter
import ReprHighlighter
43from .jupyter
import JupyterMixin, JupyterRenderable
44from .measure
import Measurement
48 from .console
import (
59 """Check if an object was created with attrs module."""
64 """Get fields for an attrs object."""
69 """Check if an instance of a dataclass contains the default repr.
72 obj (object): A dataclass instance.
75 bool: True if the default repr is used, False if there is a custom repr.
89 """Check if an instance of namedtuple contains the default repr
92 obj (object): A namedtuple
95 bool: True if the default repr is used, False if there's a custom repr.
100 except (OSError, TypeError):
105 return obj_file == default_repr_file
110 console: Optional[
"Console"] =
None,
111 overflow:
"OverflowMethod" =
"ignore",
113 indent_guides: bool =
False,
114 max_length: Optional[int] =
None,
115 max_string: Optional[int] =
None,
116 max_depth: Optional[int] =
None,
117 expand_all: bool =
False,
118) -> Union[str,
None]:
120 from .console
import ConsoleRenderable
126 console = console
or get_console()
138 indent_guides=indent_guides,
139 max_length=max_length,
140 max_string=max_string,
142 expand_all=expand_all,
155 obj: object, class_or_tuple: Union[type, Tuple[type, ...]]
157 """isinstance can fail in rare cases, for example types with no __class__"""
165 console: Optional[
"Console"] =
None,
166 overflow:
"OverflowMethod" =
"ignore",
168 indent_guides: bool =
False,
169 max_length: Optional[int] =
None,
170 max_string: Optional[int] =
None,
171 max_depth: Optional[int] =
None,
172 expand_all: bool =
False,
174 """Install automatic pretty printing in the Python REPL.
177 console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
178 overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore".
179 crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.
180 indent_guides (bool, optional): Enable indentation guides. Defaults to False.
181 max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
183 max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
184 max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
185 expand_all (bool, optional): Expand all containers. Defaults to False.
186 max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
190 console = console
or get_console()
191 assert console
is not None
194 """Replacement sys.displayhook which prettifies objects with Rich."""
195 if value
is not None:
196 assert console
is not None
204 indent_guides=indent_guides,
205 max_length=max_length,
206 max_string=max_string,
208 expand_all=expand_all,
221 def __call__(self, value: Any) -> Any:
225 console=get_console(),
227 indent_guides=indent_guides,
228 max_length=max_length,
229 max_string=max_string,
231 expand_all=expand_all,
244 """A rich renderable that pretty prints an object.
247 _object (Any): An object to pretty print.
248 highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
249 indent_size (int, optional): Number of spaces in indent. Defaults to 4.
250 justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
251 overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
252 no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
253 indent_guides (bool, optional): Enable indentation guides. Defaults to False.
254 max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
256 max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
257 max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
258 expand_all (bool, optional): Expand all containers. Defaults to False.
259 margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.
260 insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.
266 highlighter: Optional[
"HighlighterType"] =
None,
268 indent_size: int = 4,
269 justify: Optional[
"JustifyMethod"] =
None,
270 overflow: Optional[
"OverflowMethod"] =
None,
271 no_wrap: Optional[bool] =
False,
272 indent_guides: bool =
False,
273 max_length: Optional[int] =
None,
274 max_string: Optional[int] =
None,
275 max_depth: Optional[int] =
None,
276 expand_all: bool =
False,
278 insert_line: bool =
False,
283 self.justify: Optional[
"JustifyMethod"] = justify
284 self.overflow: Optional[
"OverflowMethod"] = overflow
295 self, console:
"Console", options:
"ConsoleOptions"
317 f
"{type(self._object)}.__repr__ returned empty string",
330 self, console:
"Console", options:
"ConsoleOptions"
349 f
"defaultdict({_object.default_factory!r}, {{",
351 f
"defaultdict({_object.default_factory!r}, {{}})",
356 return (f
"array({_object.typecode!r}, [",
"])", f
"array({_object.typecode!r})")
359_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {
360 os._Environ:
lambda _object: (
"environ({",
"})",
"environ({})"),
361 array: _get_braces_for_array,
362 defaultdict: _get_braces_for_defaultdict,
363 Counter:
lambda _object: (
"Counter({",
"})",
"Counter()"),
364 deque:
lambda _object: (
"deque([",
"])",
"deque()"),
365 dict:
lambda _object: (
"{",
"}",
"{}"),
366 UserDict:
lambda _object: (
"{",
"}",
"{}"),
367 frozenset:
lambda _object: (
"frozenset({",
"})",
"frozenset()"),
368 list:
lambda _object: (
"[",
"]",
"[]"),
369 UserList:
lambda _object: (
"[",
"]",
"[]"),
370 set:
lambda _object: (
"{",
"}",
"set()"),
371 tuple:
lambda _object: (
"(",
")",
"()"),
372 MappingProxyType:
lambda _object: (
"mappingproxy({",
"})",
"mappingproxy({})"),
375_MAPPING_CONTAINERS = (dict,
os._Environ, MappingProxyType, UserDict)
378def is_expandable(obj: Any) -> bool:
379 """Check if an object may be expanded by pretty print."""
382 or (is_dataclass(obj))
383 or (
hasattr(obj,
"__rich_repr__"))
385 )
and not isclass(obj)
390 """A node in a repr tree. May be atomic or a container."""
395 close_brace: str =
""
398 is_tuple: bool =
False
399 is_namedtuple: bool =
False
400 children: Optional[List[
"Node"]] =
None
401 key_separator: str =
": "
402 separator: str =
", "
405 """Generate tokens for this node."""
427 """Check the length fits within a limit.
430 start_length (int): Starting length of the line (indent, prefix, suffix).
431 max_length (int): Maximum length.
434 bool: True if the node can be rendered within max length, otherwise False.
436 total_length = start_length
438 total_length += cell_len(token)
439 if total_length > max_length:
448 self, max_width: int = 80, indent_size: int = 4, expand_all: bool =
False
450 """Render the node to a pretty repr.
453 max_width (int, optional): Maximum width of the repr. Defaults to 80.
454 indent_size (int, optional): Size of indents. Defaults to 4.
455 expand_all (bool, optional): Expand all levels. Defaults to False.
458 str: A repr string of the original object.
460 lines = [
_Line(node=self, is_root=
True)]
462 while line_no <
len(lines):
463 line = lines[line_no]
466 lines[line_no : line_no + 1] =
line.expand(indent_size)
469 repr_str =
"\n".join(str(line)
for line
in lines)
475 """A line in repr output."""
477 parent: Optional[
"_Line"] =
None
478 is_root: bool =
False
479 node: Optional[Node] =
None
483 expanded: bool =
False
488 """Check if the line may be expanded."""
489 return bool(self.
node is not None and self.
node.children)
492 """Check this line fits within a given number of cells."""
496 assert self.
node is not None
499 def expand(self, indent_size: int) -> Iterable[
"_Line"]:
500 """Expand this line by adding children on their own line."""
502 assert node
is not None
506 new_line =
yield _Line(
507 text=f
"{node.key_repr}{node.key_separator}{node.open_brace}",
508 whitespace=whitespace,
519 whitespace=child_whitespace,
521 last=last
and not tuple_of_one,
527 whitespace=whitespace,
534 return f
"{self.whitespace}{self.text}{self.node or ''}"
537 f
"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}"
542 """Checks if an object is most likely a namedtuple. It is possible
543 to craft an object that passes this check and isn't a namedtuple, but
544 there is only a minuscule chance of this happening unintentionally.
547 obj (Any): The object to test
550 bool: True if the object is a namedtuple. False otherwise.
553 fields =
getattr(obj,
"_fields",
None)
562 max_length: Optional[int] =
None,
563 max_string: Optional[int] =
None,
564 max_depth: Optional[int] =
None,
566 """Traverse object and generate a tree.
569 _object (Any): Object to be traversed.
570 max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
572 max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
574 max_depth (int, optional): Maximum depth of data structures, or None for no maximum.
578 Node: The root of a tree structure which can be used to render a pretty repr.
582 """Get repr string for an object, but catch errors."""
584 max_string
is not None
586 and len(obj) > max_string
588 truncated =
len(obj) - max_string
589 obj_repr = f
"{obj[:max_string]!r}+{truncated}"
593 except Exception
as error:
594 obj_repr = f
"<repr-error {str(error)!r}>"
597 visited_ids: Set[int] = set()
601 def _traverse(obj: Any, root: bool =
False, depth: int = 0) -> Node:
602 """Walk the object depth first."""
605 if obj_id
in visited_ids:
607 return Node(value_repr=
"...")
611 reached_max_depth = max_depth
is not None and depth >= max_depth
613 def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:
614 for arg
in rich_args:
617 key, child, default = arg
631 obj,
"awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492"
634 fake_attributes =
False
636 rich_repr_result: Optional[RichReprResult] =
None
637 if not fake_attributes:
639 if hasattr(obj,
"__rich_repr__")
and not isclass(obj):
644 if rich_repr_result
is not None:
654 if reached_max_depth:
656 node =
Node(value_repr=f
"<{class_name}...>")
658 node =
Node(value_repr=f
"{class_name}(...)")
662 open_brace=f
"<{class_name} ",
670 open_brace=f
"{class_name}(",
675 for last, arg
in loop_last(args):
678 child_node =
_traverse(child, depth=depth + 1)
684 child_node =
_traverse(arg, depth=depth + 1)
689 value_repr=f
"<{class_name}>" if angular
else f
"{class_name}()",
701 if reached_max_depth:
702 node =
Node(value_repr=f
"{obj.__class__.__name__}(...)")
705 open_brace=f
"{obj.__class__.__name__}(",
712 Tuple[str, Any, Optional[Callable[[Any], str]]]
714 """Iterate over attr fields and values."""
715 for attr
in attr_fields:
719 except Exception
as error:
729 for last, (name, value, repr_callable)
in loop_last(
iter_attrs()):
733 child_node =
_traverse(value, depth=depth + 1)
740 value_repr=f
"{obj.__class__.__name__}()", children=[], last=root
746 and not fake_attributes
752 if reached_max_depth:
753 node =
Node(value_repr=f
"{obj.__class__.__name__}(...)")
756 open_brace=f
"{obj.__class__.__name__}(",
760 empty=f
"{obj.__class__.__name__}()",
763 for last, field
in loop_last(
776 if reached_max_depth:
779 value_repr=f
"{class_name}(...)",
785 open_brace=f
"{class_name}(",
788 empty=f
"{class_name}()",
790 for last, (key, value)
in loop_last(
obj._asdict().items()):
791 child_node =
_traverse(value, depth=depth + 1)
798 for container_type
in _CONTAINERS:
800 obj_type = container_type
805 open_brace, close_brace, empty = _BRACES[obj_type](obj)
807 if reached_max_depth:
808 node =
Node(value_repr=f
"{open_brace}...{close_brace}")
814 open_brace=open_brace,
815 close_brace=close_brace,
821 last_item_index = num_items - 1
825 if max_length
is not None:
826 iter_items = islice(iter_items, max_length)
827 for index, (key, child)
in enumerate(iter_items):
828 child_node =
_traverse(child, depth=depth + 1)
833 iter_values = iter(obj)
834 if max_length
is not None:
835 iter_values = islice(iter_values, max_length)
836 for index, child
in enumerate(iter_values):
837 child_node =
_traverse(child, depth=depth + 1)
840 if max_length
is not None and num_items > max_length:
841 append(
Node(value_repr=f
"... +{num_items - max_length}", last=
True))
843 node =
Node(empty=empty, children=[], last=root)
860 indent_size: int = 4,
861 max_length: Optional[int] =
None,
862 max_string: Optional[int] =
None,
863 max_depth: Optional[int] =
None,
864 expand_all: bool =
False,
866 """Prettify repr string by expanding on to new lines to fit within a given width.
869 _object (Any): Object to repr.
870 max_width (int, optional): Desired maximum width of repr string. Defaults to 80.
871 indent_size (int, optional): Number of spaces to indent. Defaults to 4.
872 max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
874 max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
876 max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.
878 expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.
881 str: A possibly multi-line representation of the object.
888 _object, max_length=max_length, max_string=max_string, max_depth=max_depth
891 max_width=max_width, indent_size=indent_size, expand_all=expand_all
899 console: Optional[
"Console"] =
None,
900 indent_guides: bool =
True,
901 max_length: Optional[int] =
None,
902 max_string: Optional[int] =
None,
903 max_depth: Optional[int] =
None,
904 expand_all: bool =
False,
906 """A convenience function for pretty printing.
909 _object (Any): Object to pretty print.
910 console (Console, optional): Console instance, or None to use default. Defaults to None.
911 max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
913 max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.
914 max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.
915 indent_guides (bool, optional): Enable indentation guides. Defaults to True.
916 expand_all (bool, optional): Expand all containers. Defaults to False.
918 _console = get_console()
if console
is None else console
922 max_length=max_length,
923 max_string=max_string,
925 indent_guides=indent_guides,
926 expand_all=expand_all,
933if __name__ ==
"__main__":
938 return "this will fail"
940 from typing
import NamedTuple
958 {5, 6, 7, (1, 2, 3, 4), 8},
961 "defaultdict": defaultdict(
962 list, {
"crumble": [
"apple",
"rhubarb",
"butter",
"sugar",
"flour"]}
974 "atomic": (
False,
True,
None),
976 "Sparkling British Spring Water",
977 "Carbonated spring water",
980 [
"its amazing!",
"its terrible!"],
984 data[
"foo"].append(data)
992 return "Hello\x1b[38;5;239m World!"
bool check_length(self, int start_length, int max_length)
Iterable[str] iter_tokens(self)
None __init__(self, Any _object, Optional["HighlighterType"] highlighter=None, *int indent_size=4, Optional["JustifyMethod"] justify=None, Optional["OverflowMethod"] overflow=None, Optional[bool] no_wrap=False, bool indent_guides=False, Optional[int] max_length=None, Optional[int] max_string=None, Optional[int] max_depth=None, bool expand_all=False, int margin=0, bool insert_line=False)
"Measurement" __rich_measure__(self, "Console" console, "ConsoleOptions" options)
"RenderResult" __rich_console__(self, "Console" console, "ConsoleOptions" options)
bool check_length(self, int max_length)
Iterable["_Line"] expand(self, int indent_size)
bool _is_namedtuple(Any obj)
Sequence["_attr_module.Attribute[Any]"] _get_attr_fields(Any obj)
bool _is_dataclass_repr(object obj)
Tuple[str, str, str] _get_braces_for_array("array[Any]" _object)
Union[str, None] _ipy_display_hook(Any value, Optional["Console"] console=None, "OverflowMethod" overflow="ignore", bool crop=False, bool indent_guides=False, Optional[int] max_length=None, Optional[int] max_string=None, Optional[int] max_depth=None, bool expand_all=False)
bool _has_default_namedtuple_repr(object obj)
str pretty_repr(Any _object, *int max_width=80, int indent_size=4, Optional[int] max_length=None, Optional[int] max_string=None, Optional[int] max_depth=None, bool expand_all=False)
bool _is_attr_object(Any obj)
Tuple[str, str, str] _get_braces_for_defaultdict(DefaultDict[Any, Any] _object)
Node traverse(Any _object, Optional[int] max_length=None, Optional[int] max_string=None, Optional[int] max_depth=None)
bool _safe_isinstance(object obj, Union[type, Tuple[type,...]] class_or_tuple)