Skip to content

Commit f911b9f

Browse files
committed
Refactor: Allow Rich to handle expandable objects
Adds a check to prepare_objects_for_rendering() to identify expandable objects. This ensures lists, dictionaries, and other expandable types are not converted to strings prematurely, allowing them to be correctly rendered by Rich's native pretty printer.
1 parent a23926f commit f911b9f

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

cmd2/rich_utils.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
RenderableType,
2121
)
2222
from rich.padding import Padding
23+
from rich.pretty import is_expandable
2324
from rich.protocol import rich_cast
2425
from rich.segment import Segment
2526
from rich.style import StyleType
@@ -289,11 +290,14 @@ def indent(renderable: RenderableType, level: int) -> Padding:
289290
def prepare_objects_for_rendering(*objects: Any) -> tuple[Any, ...]:
290291
"""Prepare a tuple of objects for printing by Rich's Console.print().
291292
292-
This function converts any non-Rich object whose string representation contains
293-
ANSI style sequences into a Rich Text object. This ensures correct display width
294-
calculation, as Rich can then properly parse and account for these non-printing
295-
codes. All other objects are left untouched, allowing Rich's native
296-
renderers to handle them.
293+
This function processes objects to ensure they are rendered correctly by Rich.
294+
It inspects each object and, if its string representation contains ANSI style
295+
sequences, it converts the object to a Rich Text object. This ensures Rich can
296+
properly parse the non-printing codes for accurate display width calculation.
297+
298+
Objects that already implement the Rich console protocol or are expandable
299+
by its pretty printer are left untouched, as they can be handled directly by
300+
Rich's native renderers.
297301
298302
:param objects: objects to prepare
299303
:return: a tuple containing the processed objects.
@@ -305,13 +309,12 @@ def prepare_objects_for_rendering(*objects: Any) -> tuple[Any, ...]:
305309
# with a __rich__ method that might return a string.
306310
renderable = rich_cast(obj)
307311

308-
# This object implements the Rich console protocol, so no preprocessing is needed.
309-
if isinstance(renderable, ConsoleRenderable):
312+
# No preprocessing is needed for Rich-compatible or expandable objects.
313+
if isinstance(renderable, ConsoleRenderable) or is_expandable(renderable):
310314
continue
311315

316+
# Check for ANSI style sequences in its string representation.
312317
renderable_as_str = str(renderable)
313-
314-
# Check for any ANSI style sequences in the string.
315318
if ANSI_STYLE_SEQUENCE_RE.search(renderable_as_str):
316319
object_list[i] = Text.from_ansi(renderable_as_str)
317320

0 commit comments

Comments
 (0)