Let us walk on the 3-isogeny graph
Loading...
Searching...
No Matches
pip._vendor.rich.pretty Namespace Reference

Data Structures

class  _Line
 
class  BrokenRepr
 
class  Node
 
class  Pretty
 
class  StockKeepingUnit
 
class  Thing
 

Functions

bool _is_attr_object (Any obj)
 
Sequence["_attr_module.Attribute[Any]"] _get_attr_fields (Any obj)
 
bool _is_dataclass_repr (object obj)
 
bool _has_default_namedtuple_repr (object obj)
 
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 _safe_isinstance (object obj, Union[type, Tuple[type,...]] class_or_tuple)
 
None install (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)
 
Tuple[str, str, str] _get_braces_for_defaultdict (DefaultDict[Any, Any] _object)
 
Tuple[str, str, str] _get_braces_for_array ("array[Any]" _object)
 
bool is_expandable (Any obj)
 
bool _is_namedtuple (Any obj)
 
Node traverse (Any _object, Optional[int] max_length=None, Optional[int] max_string=None, Optional[int] max_depth=None)
 
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)
 
None pprint (Any _object, *Optional["Console"] console=None, bool indent_guides=True, Optional[int] max_length=None, Optional[int] max_string=None, Optional[int] max_depth=None, bool expand_all=False)
 

Variables

 _has_attrs = hasattr(_attr_module, "ib")
 
 _dummy_namedtuple = collections.namedtuple("_dummy_namedtuple", [])
 
dict _BRACES
 
 _CONTAINERS = tuple(_BRACES.keys())
 
tuple _MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)
 
 d
 
dict data
 

Function Documentation

◆ _get_attr_fields()

Sequence["_attr_module.Attribute[Any]"] _get_attr_fields ( Any  obj)
protected
Get fields for an attrs object.

Definition at line 63 of file pretty.py.

63def _get_attr_fields(obj: Any) -> Sequence["_attr_module.Attribute[Any]"]:
64 """Get fields for an attrs object."""
65 return _attr_module.fields(type(obj)) if _has_attrs else []
66
67
for i

References i.

Referenced by pip._vendor.rich.pretty.traverse().

Here is the caller graph for this function:

◆ _get_braces_for_array()

Tuple[str, str, str] _get_braces_for_array ( "array[Any]"  _object)
protected

Definition at line 355 of file pretty.py.

355def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]:
356 return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})")
357
358

◆ _get_braces_for_defaultdict()

Tuple[str, str, str] _get_braces_for_defaultdict ( DefaultDict[Any, Any]  _object)
protected

Definition at line 347 of file pretty.py.

347def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:
348 return (
349 f"defaultdict({_object.default_factory!r}, {{",
350 "})",
351 f"defaultdict({_object.default_factory!r}, {{}})",
352 )
353
354

◆ _has_default_namedtuple_repr()

bool _has_default_namedtuple_repr ( object  obj)
protected
Check if an instance of namedtuple contains the default repr

Args:
    obj (object): A namedtuple

Returns:
    bool: True if the default repr is used, False if there's a custom repr.

Definition at line 88 of file pretty.py.

88def _has_default_namedtuple_repr(obj: object) -> bool:
89 """Check if an instance of namedtuple contains the default repr
90
91 Args:
92 obj (object): A namedtuple
93
94 Returns:
95 bool: True if the default repr is used, False if there's a custom repr.
96 """
97 obj_file = None
98 try:
100 except (OSError, TypeError):
101 # OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available.
102 # TypeError trapped defensively, in case of object without filename slips through.
103 pass
105 return obj_file == default_repr_file
106
107

References i.

Referenced by pip._vendor.rich.pretty.traverse().

Here is the caller graph for this function:

◆ _ipy_display_hook()

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 
)
protected

Definition at line 108 of file pretty.py.

118) -> Union[str, None]:
119 # needed here to prevent circular import:
120 from .console import ConsoleRenderable
121
122 # always skip rich generated jupyter renderables or None values
123 if _safe_isinstance(value, JupyterRenderable) or value is None:
124 return None
125
126 console = console or get_console()
127
128 with console.capture() as capture:
129 # certain renderables should start on a new line
130 if _safe_isinstance(value, ConsoleRenderable):
133 value
134 if _safe_isinstance(value, RichRenderable)
135 else Pretty(
136 value,
137 overflow=overflow,
138 indent_guides=indent_guides,
139 max_length=max_length,
140 max_string=max_string,
141 max_depth=max_depth,
142 expand_all=expand_all,
143 margin=12,
144 ),
145 crop=crop,
146 new_line_start=True,
147 end="",
148 )
149 # strip trailing newline, not usually part of a text repr
150 # I'm not sure if this should be prevented at a lower level
151 return capture.get().rstrip("\n")
152
153

References pip._vendor.rich.pretty._safe_isinstance(), and i.

Referenced by pip._vendor.rich.pretty.install().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _is_attr_object()

bool _is_attr_object ( Any  obj)
protected
Check if an object was created with attrs module.

Definition at line 58 of file pretty.py.

58def _is_attr_object(obj: Any) -> bool:
59 """Check if an object was created with attrs module."""
60 return _has_attrs and _attr_module.has(type(obj))
61
62

References i.

Referenced by pip._vendor.rich.pretty.is_expandable(), and pip._vendor.rich.pretty.traverse().

Here is the caller graph for this function:

◆ _is_dataclass_repr()

bool _is_dataclass_repr ( object  obj)
protected
Check if an instance of a dataclass contains the default repr.

Args:
    obj (object): A dataclass instance.

Returns:
    bool: True if the default repr is used, False if there is a custom repr.

Definition at line 68 of file pretty.py.

68def _is_dataclass_repr(obj: object) -> bool:
69 """Check if an instance of a dataclass contains the default repr.
70
71 Args:
72 obj (object): A dataclass instance.
73
74 Returns:
75 bool: True if the default repr is used, False if there is a custom repr.
76 """
77 # Digging in to a lot of internals here
78 # Catching all exceptions in case something is missing on a non CPython implementation
79 try:
81 except Exception: # pragma: no coverage
82 return False
83
84

References i.

Referenced by pip._vendor.rich.pretty.traverse().

Here is the caller graph for this function:

◆ _is_namedtuple()

bool _is_namedtuple ( Any  obj)
protected
Checks if an object is most likely a namedtuple. It is possible
to craft an object that passes this check and isn't a namedtuple, but
there is only a minuscule chance of this happening unintentionally.

Args:
    obj (Any): The object to test

Returns:
    bool: True if the object is a namedtuple. False otherwise.

Definition at line 541 of file pretty.py.

541def _is_namedtuple(obj: Any) -> bool:
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.
545
546 Args:
547 obj (Any): The object to test
548
549 Returns:
550 bool: True if the object is a namedtuple. False otherwise.
551 """
552 try:
553 fields = getattr(obj, "_fields", None)
554 except Exception:
555 # Being very defensive - if we cannot get the attr then its not a namedtuple
556 return False
557 return isinstance(obj, tuple) and isinstance(fields, tuple)
558
559

References i.

Referenced by pip._vendor.rich.pretty.traverse().

Here is the caller graph for this function:

◆ _safe_isinstance()

bool _safe_isinstance ( object  obj,
Union[type, Tuple[type, ...]]   class_or_tuple 
)
protected
isinstance can fail in rare cases, for example types with no __class__

Definition at line 154 of file pretty.py.

156) -> bool:
157 """isinstance can fail in rare cases, for example types with no __class__"""
158 try:
159 return isinstance(obj, class_or_tuple)
160 except Exception:
161 return False
162
163

References i.

Referenced by pip._vendor.rich.pretty._ipy_display_hook(), pip._vendor.rich.pretty.install(), pip._vendor.rich.pretty.is_expandable(), pip._vendor.rich.pretty.pretty_repr(), and pip._vendor.rich.pretty.traverse().

Here is the caller graph for this function:

◆ install()

None install ( 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 
)
Install automatic pretty printing in the Python REPL.

Args:
    console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
    overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore".
    crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.
    indent_guides (bool, optional): Enable indentation guides. Defaults to False.
    max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
        Defaults to None.
    max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
    max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
    expand_all (bool, optional): Expand all containers. Defaults to False.
    max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.

Definition at line 164 of file pretty.py.

173) -> None:
174 """Install automatic pretty printing in the Python REPL.
175
176 Args:
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.
182 Defaults to None.
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.
187 """
188 from pip._vendor.rich import get_console
189
190 console = console or get_console()
191 assert console is not None
192
193 def display_hook(value: Any) -> None:
194 """Replacement sys.displayhook which prettifies objects with Rich."""
195 if value is not None:
196 assert console is not None
197 builtins._ = None # type: ignore[attr-defined]
199 value
200 if _safe_isinstance(value, RichRenderable)
201 else Pretty(
202 value,
203 overflow=overflow,
204 indent_guides=indent_guides,
205 max_length=max_length,
206 max_string=max_string,
207 max_depth=max_depth,
208 expand_all=expand_all,
209 ),
210 crop=crop,
211 )
212 builtins._ = value # type: ignore[attr-defined]
213
214 if "get_ipython" in globals():
215 ip = get_ipython() # type: ignore[name-defined]
216 from IPython.core.formatters import BaseFormatter
217
218 class RichFormatter(BaseFormatter): # type: ignore[misc]
219 pprint: bool = True
220
221 def __call__(self, value: Any) -> Any:
222 if self.pprint:
223 return _ipy_display_hook(
224 value,
225 console=get_console(),
226 overflow=overflow,
227 indent_guides=indent_guides,
228 max_length=max_length,
229 max_string=max_string,
230 max_depth=max_depth,
231 expand_all=expand_all,
232 )
233 else:
234 return repr(value)
235
236 # replace plain text formatter with rich formatter
237 rich_formatter = RichFormatter()
238 ip.display_formatter.formatters["text/plain"] = rich_formatter
239 else:
240 sys.displayhook = display_hook
241
242

References pip._vendor.rich.pretty._ipy_display_hook(), pip._vendor.rich.pretty._safe_isinstance(), and i.

Here is the call graph for this function:

◆ is_expandable()

bool is_expandable ( Any  obj)
Check if an object may be expanded by pretty print.

Definition at line 378 of file pretty.py.

378def is_expandable(obj: Any) -> bool:
379 """Check if an object may be expanded by pretty print."""
380 return (
381 _safe_isinstance(obj, _CONTAINERS)
382 or (is_dataclass(obj))
383 or (hasattr(obj, "__rich_repr__"))
384 or _is_attr_object(obj)
385 ) and not isclass(obj)
386
387
388@dataclass

References pip._vendor.rich.pretty._is_attr_object(), pip._vendor.rich.pretty._safe_isinstance(), and i.

Here is the call graph for this function:

◆ pprint()

None pprint ( Any  _object,
*Optional["Console"]   console = None,
bool   indent_guides = True,
Optional[int]   max_length = None,
Optional[int]   max_string = None,
Optional[int]   max_depth = None,
bool   expand_all = False 
)
A convenience function for pretty printing.

Args:
    _object (Any): Object to pretty print.
    console (Console, optional): Console instance, or None to use default. Defaults to None.
    max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
        Defaults to None.
    max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.
    max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.
    indent_guides (bool, optional): Enable indentation guides. Defaults to True.
    expand_all (bool, optional): Expand all containers. Defaults to False.

Definition at line 896 of file pretty.py.

905) -> None:
906 """A convenience function for pretty printing.
907
908 Args:
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.
912 Defaults to None.
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.
917 """
918 _console = get_console() if console is None else console
920 Pretty(
921 _object,
922 max_length=max_length,
923 max_string=max_string,
924 max_depth=max_depth,
925 indent_guides=indent_guides,
926 expand_all=expand_all,
927 overflow="ignore",
928 ),
929 soft_wrap=True,
930 )
931
932

References i.

◆ pretty_repr()

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 
)
Prettify repr string by expanding on to new lines to fit within a given width.

Args:
    _object (Any): Object to repr.
    max_width (int, optional): Desired maximum width of repr string. Defaults to 80.
    indent_size (int, optional): Number of spaces to indent. Defaults to 4.
    max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
        Defaults to None.
    max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
        Defaults to None.
    max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.
        Defaults to None.
    expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.

Returns:
    str: A possibly multi-line representation of the object.

Definition at line 856 of file pretty.py.

865) -> str:
866 """Prettify repr string by expanding on to new lines to fit within a given width.
867
868 Args:
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.
873 Defaults to None.
874 max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
875 Defaults to None.
876 max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.
877 Defaults to None.
878 expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.
879
880 Returns:
881 str: A possibly multi-line representation of the object.
882 """
883
884 if _safe_isinstance(_object, Node):
885 node = _object
886 else:
887 node = traverse(
888 _object, max_length=max_length, max_string=max_string, max_depth=max_depth
889 )
890 repr_str: str = node.render(
891 max_width=max_width, indent_size=indent_size, expand_all=expand_all
892 )
893 return repr_str
894
895

References pip._vendor.rich.pretty._safe_isinstance(), i, and pip._vendor.rich.pretty.traverse().

Referenced by Pretty.__rich_console__(), and Pretty.__rich_measure__().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ traverse()

Node traverse ( Any  _object,
Optional[int]   max_length = None,
Optional[int]   max_string = None,
Optional[int]   max_depth = None 
)
Traverse object and generate a tree.

Args:
    _object (Any): Object to be traversed.
    max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
        Defaults to None.
    max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
        Defaults to None.
    max_depth (int, optional): Maximum depth of data structures, or None for no maximum.
        Defaults to None.

Returns:
    Node: The root of a tree structure which can be used to render a pretty repr.

Definition at line 560 of file pretty.py.

565) -> Node:
566 """Traverse object and generate a tree.
567
568 Args:
569 _object (Any): Object to be traversed.
570 max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
571 Defaults to None.
572 max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
573 Defaults to None.
574 max_depth (int, optional): Maximum depth of data structures, or None for no maximum.
575 Defaults to None.
576
577 Returns:
578 Node: The root of a tree structure which can be used to render a pretty repr.
579 """
580
581 def to_repr(obj: Any) -> str:
582 """Get repr string for an object, but catch errors."""
583 if (
584 max_string is not None
585 and _safe_isinstance(obj, (bytes, str))
586 and len(obj) > max_string
587 ):
588 truncated = len(obj) - max_string
589 obj_repr = f"{obj[:max_string]!r}+{truncated}"
590 else:
591 try:
592 obj_repr = repr(obj)
593 except Exception as error:
594 obj_repr = f"<repr-error {str(error)!r}>"
595 return obj_repr
596
597 visited_ids: Set[int] = set()
598 push_visited = visited_ids.add
599 pop_visited = visited_ids.remove
600
601 def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:
602 """Walk the object depth first."""
603
604 obj_id = id(obj)
605 if obj_id in visited_ids:
606 # Recursion detected
607 return Node(value_repr="...")
608
609 obj_type = type(obj)
610 children: List[Node]
611 reached_max_depth = max_depth is not None and depth >= max_depth
612
613 def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:
614 for arg in rich_args:
615 if _safe_isinstance(arg, tuple):
616 if len(arg) == 3:
617 key, child, default = arg
618 if default == child:
619 continue
620 yield key, child
621 elif len(arg) == 2:
622 key, child = arg
623 yield key, child
624 elif len(arg) == 1:
625 yield arg[0]
626 else:
627 yield arg
628
629 try:
630 fake_attributes = hasattr(
631 obj, "awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492"
632 )
633 except Exception:
634 fake_attributes = False
635
636 rich_repr_result: Optional[RichReprResult] = None
637 if not fake_attributes:
638 try:
639 if hasattr(obj, "__rich_repr__") and not isclass(obj):
640 rich_repr_result = obj.__rich_repr__()
641 except Exception:
642 pass
643
644 if rich_repr_result is not None:
645 push_visited(obj_id)
646 angular = getattr(obj.__rich_repr__, "angular", False)
647 args = list(iter_rich_args(rich_repr_result))
648 class_name = obj.__class__.__name__
649
650 if args:
651 children = []
652 append = children.append
653
654 if reached_max_depth:
655 if angular:
656 node = Node(value_repr=f"<{class_name}...>")
657 else:
658 node = Node(value_repr=f"{class_name}(...)")
659 else:
660 if angular:
661 node = Node(
662 open_brace=f"<{class_name} ",
663 close_brace=">",
664 children=children,
665 last=root,
666 separator=" ",
667 )
668 else:
669 node = Node(
670 open_brace=f"{class_name}(",
671 close_brace=")",
672 children=children,
673 last=root,
674 )
675 for last, arg in loop_last(args):
676 if _safe_isinstance(arg, tuple):
677 key, child = arg
678 child_node = _traverse(child, depth=depth + 1)
679 child_node.last = last
682 append(child_node)
683 else:
684 child_node = _traverse(arg, depth=depth + 1)
685 child_node.last = last
686 append(child_node)
687 else:
688 node = Node(
689 value_repr=f"<{class_name}>" if angular else f"{class_name}()",
690 children=[],
691 last=root,
692 )
693 pop_visited(obj_id)
694 elif _is_attr_object(obj) and not fake_attributes:
695 push_visited(obj_id)
696 children = []
697 append = children.append
698
699 attr_fields = _get_attr_fields(obj)
700 if attr_fields:
701 if reached_max_depth:
702 node = Node(value_repr=f"{obj.__class__.__name__}(...)")
703 else:
704 node = Node(
705 open_brace=f"{obj.__class__.__name__}(",
706 close_brace=")",
707 children=children,
708 last=root,
709 )
710
711 def iter_attrs() -> Iterable[
712 Tuple[str, Any, Optional[Callable[[Any], str]]]
713 ]:
714 """Iterate over attr fields and values."""
715 for attr in attr_fields:
716 if attr.repr:
717 try:
718 value = getattr(obj, attr.name)
719 except Exception as error:
720 # Can happen, albeit rarely
721 yield (attr.name, error, None)
722 else:
723 yield (
724 attr.name,
725 value,
726 attr.repr if callable(attr.repr) else None,
727 )
728
729 for last, (name, value, repr_callable) in loop_last(iter_attrs()):
730 if repr_callable:
731 child_node = Node(value_repr=str(repr_callable(value)))
732 else:
733 child_node = _traverse(value, depth=depth + 1)
734 child_node.last = last
737 append(child_node)
738 else:
739 node = Node(
740 value_repr=f"{obj.__class__.__name__}()", children=[], last=root
741 )
742 pop_visited(obj_id)
743 elif (
744 is_dataclass(obj)
745 and not _safe_isinstance(obj, type)
746 and not fake_attributes
747 and _is_dataclass_repr(obj)
748 ):
749 push_visited(obj_id)
750 children = []
751 append = children.append
752 if reached_max_depth:
753 node = Node(value_repr=f"{obj.__class__.__name__}(...)")
754 else:
755 node = Node(
756 open_brace=f"{obj.__class__.__name__}(",
757 close_brace=")",
758 children=children,
759 last=root,
760 empty=f"{obj.__class__.__name__}()",
761 )
762
763 for last, field in loop_last(
764 field for field in fields(obj) if field.repr
765 ):
766 child_node = _traverse(getattr(obj, field.name), depth=depth + 1)
768 child_node.last = last
770 append(child_node)
771
772 pop_visited(obj_id)
773 elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj):
774 push_visited(obj_id)
775 class_name = obj.__class__.__name__
776 if reached_max_depth:
777 # If we've reached the max depth, we still show the class name, but not its contents
778 node = Node(
779 value_repr=f"{class_name}(...)",
780 )
781 else:
782 children = []
783 append = children.append
784 node = Node(
785 open_brace=f"{class_name}(",
786 close_brace=")",
787 children=children,
788 empty=f"{class_name}()",
789 )
790 for last, (key, value) in loop_last(obj._asdict().items()):
791 child_node = _traverse(value, depth=depth + 1)
793 child_node.last = last
795 append(child_node)
796 pop_visited(obj_id)
797 elif _safe_isinstance(obj, _CONTAINERS):
798 for container_type in _CONTAINERS:
799 if _safe_isinstance(obj, container_type):
800 obj_type = container_type
801 break
802
803 push_visited(obj_id)
804
805 open_brace, close_brace, empty = _BRACES[obj_type](obj)
806
807 if reached_max_depth:
808 node = Node(value_repr=f"{open_brace}...{close_brace}")
809 elif obj_type.__repr__ != type(obj).__repr__:
810 node = Node(value_repr=to_repr(obj), last=root)
811 elif obj:
812 children = []
813 node = Node(
814 open_brace=open_brace,
815 close_brace=close_brace,
816 children=children,
817 last=root,
818 )
819 append = children.append
820 num_items = len(obj)
821 last_item_index = num_items - 1
822
823 if _safe_isinstance(obj, _MAPPING_CONTAINERS):
824 iter_items = iter(obj.items())
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)
830 child_node.last = index == last_item_index
831 append(child_node)
832 else:
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)
838 child_node.last = index == last_item_index
839 append(child_node)
840 if max_length is not None and num_items > max_length:
841 append(Node(value_repr=f"... +{num_items - max_length}", last=True))
842 else:
843 node = Node(empty=empty, children=[], last=root)
844
845 pop_visited(obj_id)
846 else:
847 node = Node(value_repr=to_repr(obj), last=root)
848 node.is_tuple = _safe_isinstance(obj, tuple)
849 node.is_namedtuple = _is_namedtuple(obj)
850 return node
851
852 node = _traverse(_object, root=True)
853 return node
854
855

References pip._vendor.rich.pretty._get_attr_fields(), pip._vendor.rich.pretty._has_default_namedtuple_repr(), pip._vendor.rich.pretty._is_attr_object(), pip._vendor.rich.pretty._is_dataclass_repr(), pip._vendor.rich.pretty._is_namedtuple(), pip._vendor.rich.pretty._safe_isinstance(), and i.

Referenced by pip._vendor.rich.pretty.pretty_repr().

Here is the call graph for this function:
Here is the caller graph for this function:

Variable Documentation

◆ _BRACES

dict _BRACES
protected
Initial value:
1= {
2 os._Environ: lambda _object: ("environ({", "})", "environ({})"),
3 array: _get_braces_for_array,
4 defaultdict: _get_braces_for_defaultdict,
5 Counter: lambda _object: ("Counter({", "})", "Counter()"),
6 deque: lambda _object: ("deque([", "])", "deque()"),
7 dict: lambda _object: ("{", "}", "{}"),
8 UserDict: lambda _object: ("{", "}", "{}"),
9 frozenset: lambda _object: ("frozenset({", "})", "frozenset()"),
10 list: lambda _object: ("[", "]", "[]"),
11 UserList: lambda _object: ("[", "]", "[]"),
12 set: lambda _object: ("{", "}", "set()"),
13 tuple: lambda _object: ("(", ")", "()"),
14 MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"),
15}

Definition at line 359 of file pretty.py.

◆ _CONTAINERS

_CONTAINERS = tuple(_BRACES.keys())
protected

Definition at line 374 of file pretty.py.

◆ _dummy_namedtuple

_dummy_namedtuple = collections.namedtuple("_dummy_namedtuple", [])
protected

Definition at line 85 of file pretty.py.

◆ _has_attrs

bool _has_attrs = hasattr(_attr_module, "ib")
protected

Definition at line 33 of file pretty.py.

◆ _MAPPING_CONTAINERS

tuple _MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)
protected

Definition at line 375 of file pretty.py.

◆ d

d

Definition at line 949 of file pretty.py.

◆ data

dict data

Definition at line 951 of file pretty.py.