Prepare a tuple of objects for printing by Rich's Console.print(). This function processes objects to ensure they are rendered correctly by Rich. It inspects each object and, if its string representation contains ANSI style sequences, it converts the object to a Rich Text object. This e
(*objects: Any)
| 695 | |
| 696 | |
| 697 | def prepare_objects_for_rendering(*objects: Any) -> tuple[Any, ...]: |
| 698 | """Prepare a tuple of objects for printing by Rich's Console.print(). |
| 699 | |
| 700 | This function processes objects to ensure they are rendered correctly by Rich. |
| 701 | It inspects each object and, if its string representation contains ANSI style |
| 702 | sequences, it converts the object to a Rich Text object. This ensures Rich can |
| 703 | properly parse the non-printing codes for accurate display width calculation. |
| 704 | |
| 705 | Objects that already implement the Rich console protocol or are expandable |
| 706 | by its pretty printer are left untouched, as they can be handled directly by |
| 707 | Rich's native renderers. |
| 708 | |
| 709 | :param objects: objects to prepare |
| 710 | :return: a tuple containing the processed objects. |
| 711 | """ |
| 712 | object_list = list(objects) |
| 713 | |
| 714 | for i, obj in enumerate(object_list): |
| 715 | # Resolve the object's final renderable form, including those |
| 716 | # with a __rich__ method that might return a string. |
| 717 | renderable = rich_cast(obj) |
| 718 | |
| 719 | # No preprocessing is needed for Rich-compatible or expandable objects. |
| 720 | if isinstance(renderable, ConsoleRenderable) or is_expandable(renderable): |
| 721 | continue |
| 722 | |
| 723 | # Check for ANSI style sequences in its string representation. |
| 724 | renderable_as_str = str(renderable) |
| 725 | if ANSI_STYLE_SEQUENCE_RE.search(renderable_as_str): |
| 726 | object_list[i] = Text.from_ansi(renderable_as_str) |
| 727 | |
| 728 | return tuple(object_list) |