failed CONTEXT NO_PATCH UNSUBMITTED agent_error · 17 tool calls · 69 s · Textualize/rich
perf: reduce Console and RichHandler import time by deferring unused imports ## E2E Results | Import | master | This PR | Speedup | |---|---|---|---| | `from rich.console import Console` | 78.1ms | 52.2ms | **1.50x faster** | | `from rich.logging import RichHandler` | 99.4ms | 56.9ms | **1.75x faster** | | `import rich` | 18.2ms | 18.3ms | (already lean) | ## Summary Defer module-level imports that are only needed in specific code paths, move annotation-only imports to `TYPE_CHECKING`, and remove dead code: | File | Change | Savings | |---|---|---| | `logging.py` | Defer `Traceback` to `emit()` (only when `rich_tracebacks=True`) | ~20ms | | `logging.py` | `from __future__ import annotations` + `TYPE_CHECKING` for `Console`, `ConsoleRenderable`, `Highlighter`, `FormatTimeCallable` | ~6ms | | `logging.py` | Replace `pathlib.Path` → `os.path.basename` (also a minor runtime win) | ~4-5ms | | `console.py` | Eliminate `import inspect`; replace `isclass` → `isinstance(x, type)`, `currentframe` → `sys._getframe` | ~10ms | | `console.py` | Defer `pretty` to `Console.print()` | ~3-5ms | | `console.py` | Defer `scope` to `Console.log()` (only when `log_locals=True`) | ~3-5ms | | `console.py` | Defer `getpass` to `Console.input()` (only when `password=True`) | ~2ms | | `console.py` | Defer `html.escape` and `zlib` to export methods | ~2.3ms | | `console.py` | Remove dead `_svg_hash` function (unused since 113997ac, fixes latent NameError) | cleanup | | `segment.py` | Remove dead `logging` import (`getLogger` assigned but never used) | ~2-3ms | | `theme.py` | Defer `configparser` to `Theme.from_file()` | ~1.5ms | | `syntax.py` | Move `Console`, `ConsoleOptions`, `JustifyMethod`, `RenderResult` to `TYPE_CHECKING` | eliminates console.py from syntax import chain | | `protocol.py` | Replace `from inspect import isclass` → `isinstance(x, type)` | prepares for dataclasses removal | | `repr.py` | Defer `import inspect` to `auto_rich_repr()` | prepares for dataclasses removal | All deferred imports are still available at runtime — they're loaded when the code path that needs them is actually hit. The `TYPE_CHECKING` imports are annotation-only and never needed at runtime (files use `from __future__ import annotations`). ## Benchmarks Environment: Standard_D2s_v5 (non-burstable), CPython 3.13.13, hyperfine --min-runs 30 ### Per-module breakdown (this PR) | Module | Time | |---|---| | `import rich` | 18.2ms | | `Console` | 52.5ms | | `RichHandler` | 56.4ms | | `Syntax` | 64.7ms | | `Traceback` | 92.5ms | | `Markdown` | 103.0ms | ## Motivation pip vendors Rich, and `Console`/`RichHandler` are imported on every `pip` invocation. These savings directly improve startup time for pip and every other tool that imports Rich. ## Testing - `pytest tests/` — 952 passed, 25 skipped - `mypy -p rich --no-incremental` — no issues - `black --check` — passes ## Disclosure This PR was developed with AI assistance (codeflash-agent). Benchmarked in a controlled environment (dedicated non-burstable Azure VM). All tests verified across multiple Python implementations.
| # | Tool | Arguments | Result |
|---|---|---|---|
| 1 | run_command | {
"command": "ls -R rich/"
} | {"status": "ok", "stdout": "rich/:\n__init__.py\n__main__.py\n_emoji_codes.py\n_emoji_replace.py\n_export_format.py\n_extension.py\n_fileno.py\n_inspect.py\n_lofull{"status": "ok", "stdout": "rich/:\n__init__.py\n__main__.py\n_emoji_codes.py\n_emoji_replace.py\n_export_format.py\n_extension.py\n_fileno.py\n_inspect.py\n_log_render.py\n_loop.py\n_null_file.py\n_palettes.py\n_pick.py\n_ratio.py\n_spinners.py\n_stack.py\n_timer.py\n_unicode_data\n_win32_console.py\n_windows.py\n_windows_renderer.py\n_wrap.py\nabc.py\nalign.py\nansi.py\nbar.py\nbox.py\ncells.py\ncolor.py\ncolor_triplet.py\ncolumns.py\nconsole.py\nconstrain.py\ncontainers.py\ncontrol.py\ndefault_styles.py\ndiagnose.py\nemoji.py\nerrors.py\nfile_proxy.py\nfilesize.py\nhighlighter.py\njson.py\njupyter.py\nlayout.py\nlive.py\nlive_render.py\nlogging.py\nmarkdown.py\nmarkup.py\nmeasure.py\npadding.py\npager.py\npalette.py\npanel.py\npretty.py\nprogress.py\nprogress_bar.py\nprompt.py\nprotocol.py\npy.typed\nregion.py\nrepr.py\nrule.py\nscope.py\nscreen.py\nsegment.py\nspinner.py\nstatus.py\nstyle.py\nstyled.py\nsyntax.py\ntable.py\nterminal_theme.py\ntext.py\ntheme.py\nthemes.py\ntraceback.py\ntree.py\n\nrich/_unicode_data:\n__init__.py\n_versions.py\nunicode10-0-0.py\nunicode11-0-0.py\nunicode12-0-0.py\nunicode12-1-0.py\nunicode13-0-0.py\nunicode14-0-0.py\nunicode15-0-0.py\nunicode15-1-0.py\nunicode16-0-0.py\nunicode17-0-0.py\nunicode4-1-0.py\nunicode5-0-0.py\nunicode5-1-0.py\nunicode5-2-0.py\nunicode6-0-0.py\nunicode6-1-0.py\nunicode6-2-0.py\nunicode6-3-0.py\nunicode7-0-0.py\nunicode8-0-0.py\nunicode9-0-0.py\n", "stderr": "", "exit_code": 0} |
| 2 | read_file | {
"filepath": "rich/logging.py"
} | {"status": "ok", "filepath": "rich/logging.py", "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib full{"status": "ok", "filepath": "rich/logging.py", "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import ClassVar, Iterable, List, Optional, Type, Union\n\nfrom rich._null_file import NullFile\n\nfrom . import get_console\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .console import Console, ConsoleRenderable\nfrom .highlighter import Highlighter, ReprHighlighter\nfrom .text import Text\nfrom .traceback import Traceback\n\n\nclass RichHandler(Handler):\n \"\"\"A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.\n The level is color coded, and the message is syntax highlighted.\n\n Note:\n Be careful when enabling console markup in log messages if you have configured logging for libraries not\n under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.\n\n Args:\n level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.\n console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.\n Default will use a global console instance writing to stdout.\n show_time (bool, optional): Show a column for the time. Defaults to True.\n omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.\n show_level (bool, optional): Show a column for the level. Defaults to True.\n show_path (bool, optional): Show the path to the original log call. Defaults to True.\n enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.\n highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.\n markup (bool, optional): Enable console markup in log messages. Defaults to Fals |
| 3 | read_file | {
"filepath": "rich/logging.py",
"start_line\"": "151",
"end_line\"": "297"
} | {"status": "ok", "filepath": "rich/logging.py", "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib full{"status": "ok", "filepath": "rich/logging.py", "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import ClassVar, Iterable, List, Optional, Type, Union\n\nfrom rich._null_file import NullFile\n\nfrom . import get_console\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .console import Console, ConsoleRenderable\nfrom .highlighter import Highlighter, ReprHighlighter\nfrom .text import Text\nfrom .traceback import Traceback\n\n\nclass RichHandler(Handler):\n \"\"\"A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.\n The level is color coded, and the message is syntax highlighted.\n\n Note:\n Be careful when enabling console markup in log messages if you have configured logging for libraries not\n under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.\n\n Args:\n level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.\n console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.\n Default will use a global console instance writing to stdout.\n show_time (bool, optional): Show a column for the time. Defaults to True.\n omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.\n show_level (bool, optional): Show a column for the level. Defaults to True.\n show_path (bool, optional): Show the path to the original log call. Defaults to True.\n enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.\n highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.\n markup (bool, optional): Enable console markup in log messages. Defaults to Fals |
| 4 | read_file | {
"filepath": "rich/logging.py"
} | {"status": "ok", "filepath": "rich/logging.py", "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib full{"status": "ok", "filepath": "rich/logging.py", "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import ClassVar, Iterable, List, Optional, Type, Union\n\nfrom rich._null_file import NullFile\n\nfrom . import get_console\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .console import Console, ConsoleRenderable\nfrom .highlighter import Highlighter, ReprHighlighter\nfrom .text import Text\nfrom .traceback import Traceback\n\n\nclass RichHandler(Handler):\n \"\"\"A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.\n The level is color coded, and the message is syntax highlighted.\n\n Note:\n Be careful when enabling console markup in log messages if you have configured logging for libraries not\n under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.\n\n Args:\n level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.\n console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.\n Default will use a global console instance writing to stdout.\n show_time (bool, optional): Show a column for the time. Defaults to True.\n omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.\n show_level (bool, optional): Show a column for the level. Defaults to True.\n show_path (bool, optional): Show the path to the original log call. Defaults to True.\n enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.\n highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.\n markup (bool, optional): Enable console markup in log messages. Defaults to Fals |
| 5 | read_file | {
"filepath": "rich/logging.py",
"start_line": "151"
} | {"status": "error", "error_type": "FileReadError", "error_message": "'>' not supported between instances of 'int' and 'str'"}full{"status": "error", "error_type": "FileReadError", "error_message": "'>' not supported between instances of 'int' and 'str'"} |
| 6 | read_file | {
"filepath": "rich/logging.py",
"start_line": "151",
"end_line": "297"
} | {"status": "error", "error_type": "FileReadError", "error_message": "'>' not supported between instances of 'int' and 'str'"}full{"status": "error", "error_type": "FileReadError", "error_message": "'>' not supported between instances of 'int' and 'str'"} |
| 7-8 ×2 | run_command | {
"command": "cat rich/logging.py"
} | {"status": "ok", "stdout": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import Mfull{"status": "ok", "stdout": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import ClassVar, Iterable, List, Optional, Type, Union\n\nfrom rich._null_file import NullFile\n\nfrom . import get_console\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .console import Console, ConsoleRenderable\nfrom .highlighter import Highlighter, ReprHighlighter\nfrom .text import Text\nfrom .traceback import Traceback\n\n\nclass RichHandler(Handler):\n \"\"\"A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.\n The level is color coded, and the message is syntax highlighted.\n\n Note:\n Be careful when enabling console markup in log messages if you have configured logging for libraries not\n under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.\n\n Args:\n level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.\n console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.\n Default will use a global console instance writing to stdout.\n show_time (bool, optional): Show a column for the time. Defaults to True.\n omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.\n show_level (bool, optional): Show a column for the level. Defaults to True.\n show_path (bool, optional): Show the path to the original log call. Defaults to True.\n enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.\n highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.\n markup (bool, optional): Enable console markup in log messages. Defaults to False.\n rich_tracebacks (boo |
| 9 | run_command | {
"command": "cat rich/logging.py | head -n 300"
} | {"status": "ok", "stdout": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import Mfull{"status": "ok", "stdout": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import ClassVar, Iterable, List, Optional, Type, Union\n\nfrom rich._null_file import NullFile\n\nfrom . import get_console\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .console import Console, ConsoleRenderable\nfrom .highlighter import Highlighter, ReprHighlighter\nfrom .text import Text\nfrom .traceback import Traceback\n\n\nclass RichHandler(Handler):\n \"\"\"A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.\n The level is color coded, and the message is syntax highlighted.\n\n Note:\n Be careful when enabling console markup in log messages if you have configured logging for libraries not\n under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.\n\n Args:\n level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.\n console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.\n Default will use a global console instance writing to stdout.\n show_time (bool, optional): Show a column for the time. Defaults to True.\n omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.\n show_level (bool, optional): Show a column for the level. Defaults to True.\n show_path (bool, optional): Show the path to the original log call. Defaults to True.\n enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.\n highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.\n markup (bool, optional): Enable console markup in log messages. Defaults to False.\n rich_tracebacks (boo |
| 10 | run_command | {
"command": "cat rich/logging.py | tail -n 200"
} | {"status": "ok", "stdout": " time_format=log_time_format,\n omit_repeated_times=omit_repeated_times,\n level_width=None,\n )\n self.enable_link_path = enable_lifull{"status": "ok", "stdout": " time_format=log_time_format,\n omit_repeated_times=omit_repeated_times,\n level_width=None,\n )\n self.enable_link_path = enable_link_path\n self.markup = markup\n self.rich_tracebacks = rich_tracebacks\n self.tracebacks_width = tracebacks_width\n self.tracebacks_extra_lines = tracebacks_extra_lines\n self.tracebacks_theme = tracebacks_theme\n self.tracebacks_word_wrap = tracebacks_word_wrap\n self.tracebacks_show_locals = tracebacks_show_locals\n self.tracebacks_suppress = tracebacks_suppress\n self.tracebacks_max_frames = tracebacks_max_frames\n self.tracebacks_code_width = tracebacks_code_width\n self.locals_max_length = locals_max_length\n self.locals_max_string = locals_max_string\n self.keywords = keywords\n\n def get_level_text(self, record: LogRecord) -> Text:\n \"\"\"Get the level name from the record.\n\n Args:\n record (LogRecord): LogRecord instance.\n\n Returns:\n Text: A tuple of the style and level name.\n \"\"\"\n level_name = record.levelname\n level_text = Text.styled(\n level_name.ljust(8), f\"logging.level.{level_name.lower()}\"\n )\n return level_text\n\n def emit(self, record: LogRecord) -> None:\n \"\"\"Invoked by logging.\"\"\"\n message = self.format(record)\n traceback = None\n if (\n self.rich_tracebacks\n and record.exc_info\n and record.exc_info != (None, None, None)\n ):\n exc_type, exc_value, exc_traceback = record.exc_info\n assert exc_type is not None\n assert exc_value is not None\n traceback = Traceback.from_exception(\n exc_type,\n exc_value,\n exc_traceback,\n width=self.tracebacks_width,\n |
| 11 | run_command | {
"command": "cat rich/logging.py | tail -n 100"
} | {"status": "ok", "stdout": "\n if self.keywords is None:\n self.keywords = self.KEYWORDS\n\n if self.keywords:\n message_text.highlight_words(self.keywords, \"lfull{"status": "ok", "stdout": "\n if self.keywords is None:\n self.keywords = self.KEYWORDS\n\n if self.keywords:\n message_text.highlight_words(self.keywords, \"logging.keyword\")\n\n return message_text\n\n def render(\n self,\n *,\n record: LogRecord,\n traceback: Optional[Traceback],\n message_renderable: \"ConsoleRenderable\",\n ) -> \"ConsoleRenderable\":\n \"\"\"Render log for display.\n\n Args:\n record (LogRecord): logging Record.\n traceback (Optional[Traceback]): Traceback instance or None for no Traceback.\n message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.\n\n Returns:\n ConsoleRenderable: Renderable to display log.\n \"\"\"\n path = Path(record.pathname).name\n level = self.get_level_text(record)\n time_format = None if self.formatter is None else self.formatter.datefmt\n log_time = datetime.fromtimestamp(record.created)\n\n log_renderable = self._log_render(\n self.console,\n [message_renderable] if not traceback else [message_renderable, traceback],\n log_time=log_time,\n time_format=time_format,\n level=level,\n path=path,\n line_no=record.lineno,\n link_path=record.pathname if self.enable_link_path else None,\n )\n return log_renderable\n\n\nif __name__ == \"__main__\": # pragma: no cover\n from time import sleep\n\n FORMAT = \"%(message)s\"\n # FORMAT = \"%(asctime)-15s - %(levelname)s - %(message)s\"\n logging.basicConfig(\n level=\"NOTSET\",\n format=FORMAT,\n datefmt=\"[%X]\",\n handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],\n )\n log = logging.getLogger(\"rich\")\n\n log.info(\"Server starting...\")\n log.info(\"Listening on http |
| 12 | read_file | {
"filepath": "rich/console.py"
} | {"status": "ok", "filepath": "rich/console.py", "content": "import inspect\nimport os\nimport sys\nimport threading\nimport zlib\nfrom abc import ABC, abstractmfull{"status": "ok", "filepath": "rich/console.py", "content": "import inspect\nimport os\nimport sys\nimport threading\nimport zlib\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom functools import wraps\nfrom getpass import getpass\nfrom html import escape\nfrom inspect import isclass\nfrom itertools import islice\nfrom math import ceil\nfrom time import monotonic\nfrom types import FrameType, ModuleType, TracebackType\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n Iterable,\n List,\n Literal,\n Mapping,\n NamedTuple,\n Optional,\n Protocol,\n TextIO,\n Tuple,\n Type,\n Union,\n cast,\n runtime_checkable,\n)\n\nfrom rich._null_file import NULL_FILE\n\nfrom . import errors, themes\nfrom ._emoji_replace import _emoji_replace\nfrom ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT\nfrom ._fileno import get_fileno\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .align import Align, AlignMethod\nfrom .color import ColorSystem, blend_rgb\nfrom .control import Control\nfrom .emoji import EmojiVariant\nfrom .highlighter import NullHighlighter, ReprHighlighter\nfrom .markup import render as render_markup\nfrom .measure import Measurement, measure_renderables\nfrom .pager import Pager, SystemPager\nfrom .pretty import Pretty, is_expandable\nfrom .protocol import rich_cast\nfrom .region import Region\nfrom .scope import render_scope\nfrom .screen import Screen\nfrom .segment import Segment\nfrom .style import Style, StyleType\nfrom .styled import Styled\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme\nfrom .text import Text, TextType\nfrom .theme import Theme, ThemeStack\n\nif TYPE_CHECKING:\n from ._windows import WindowsConsoleFeatures\n from .live import Live\n from .status import Status\n\nJUPYTER_DEFAULT_COLUMNS = 115\nJUPYTER_DEFAULT_LINES = 100\nWINDOWS = |
| 13 | run_command | {
"command": "grep -n \"_svg_hash\" rich/console.py"
} | {"status": "ok", "stdout": "2619:def _svg_hash(svg_main_code: str) -> str:\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "2619:def _svg_hash(svg_main_code: str) -> str:\n", "stderr": "", "exit_code": 0} |
| 14 | read_file | {
"filepath": "rich/segment.py"
} | {"status": "ok", "filepath": "rich/segment.py", "content": "from enum import IntEnum\nfrom functools import lru_cache\nfrom itertools import filterfalse\nfrom lfull{"status": "ok", "filepath": "rich/segment.py", "content": "from enum import IntEnum\nfrom functools import lru_cache\nfrom itertools import filterfalse\nfrom logging import getLogger\nfrom operator import attrgetter\nfrom typing import (\n TYPE_CHECKING,\n Dict,\n Iterable,\n List,\n NamedTuple,\n Optional,\n Sequence,\n Tuple,\n Type,\n Union,\n)\n\nfrom .cells import (\n _is_single_cell_widths,\n cached_cell_len,\n cell_len,\n get_character_cell_size,\n set_cell_size,\n)\nfrom .repr import Result, rich_repr\nfrom .style import Style\n\nif TYPE_CHECKING:\n from .console import Console, ConsoleOptions, RenderResult\n\nlog = getLogger(\"rich\")\n\n\nclass ControlType(IntEnum):\n \"\"\"Non-printable control codes which typically translate to ANSI codes.\"\"\"\n\n BELL = 1\n CARRIAGE_RETURN = 2\n HOME = 3\n CLEAR = 4\n SHOW_CURSOR = 5\n HIDE_CURSOR = 6\n ENABLE_ALT_SCREEN = 7\n DISABLE_ALT_SCREEN = 8\n CURSOR_UP = 9\n CURSOR_DOWN = 10\n CURSOR_FORWARD = 11\n CURSOR_BACKWARD = 12\n CURSOR_MOVE_TO_COLUMN = 13\n CURSOR_MOVE_TO = 14\n ERASE_IN_LINE = 15\n SET_WINDOW_TITLE = 16\n\n\nControlCode = Union[\n Tuple[ControlType],\n Tuple[ControlType, Union[int, str]],\n Tuple[ControlType, int, int],\n]\n\n\n@rich_repr()\nclass Segment(NamedTuple):\n \"\"\"A piece of text with associated style. Segments are produced by the Console render process and\n are ultimately converted in to strings to be written to the terminal.\n\n Args:\n text (str): A piece of text.\n style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.\n control (Tuple[ControlCode], optional): Optional sequence of control codes.\n\n Attributes:\n cell_length (int): The cell length of this Segment.\n \"\"\"\n\n text: str\n style: Optional[Style] = None\n control: Optional[Sequence[ControlCode]] = None\n\n @property\n def c |
| 15 | read_file | {
"filepath": "rich/theme.py"
} | {"status": "ok", "filepath": "rich/theme.py", "content": "import configparser\nfrom typing import IO, Dict, List, Mapping, Optional\n\nfrom .default_styles impofull{"status": "ok", "filepath": "rich/theme.py", "content": "import configparser\nfrom typing import IO, Dict, List, Mapping, Optional\n\nfrom .default_styles import DEFAULT_STYLES\nfrom .style import Style, StyleType\n\n\nclass Theme:\n \"\"\"A container for style information, used by :class:`~rich.console.Console`.\n\n Args:\n styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for a theme with no styles.\n inherit (bool, optional): Inherit default styles. Defaults to True.\n \"\"\"\n\n styles: Dict[str, Style]\n\n def __init__(\n self, styles: Optional[Mapping[str, StyleType]] = None, inherit: bool = True\n ):\n self.styles = DEFAULT_STYLES.copy() if inherit else {}\n if styles is not None:\n self.styles.update(\n {\n name: style if isinstance(style, Style) else Style.parse(style)\n for name, style in styles.items()\n }\n )\n\n @property\n def config(self) -> str:\n \"\"\"Get contents of a config file for this theme.\"\"\"\n config = \"[styles]\\n\" + \"\\n\".join(\n f\"{name} = {style}\" for name, style in sorted(self.styles.items())\n )\n return config\n\n @classmethod\n def from_file(\n cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True\n ) -> \"Theme\":\n \"\"\"Load a theme from a text mode file.\n\n Args:\n config_file (IO[str]): An open conf file.\n source (str, optional): The filename of the open file. Defaults to None.\n inherit (bool, optional): Inherit default styles. Defaults to True.\n\n Returns:\n Theme: A New theme instance.\n \"\"\"\n config = configparser.ConfigParser()\n config.read_file(config_file, source=source)\n styles = {name: Style.parse(value) for name, value in config.items(\"styles |
| 16 | read_file | {
"filepath": "rich/syntax.py"
} | {"status": "ok", "filepath": "rich/syntax.py", "content": "from __future__ import annotations\n\nimport os.path\nimport re\nimport sys\nimport textwrap\nfrom abfull{"status": "ok", "filepath": "rich/syntax.py", "content": "from __future__ import annotations\n\nimport os.path\nimport re\nimport sys\nimport textwrap\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\nfrom typing import (\n Any,\n Dict,\n Iterable,\n List,\n NamedTuple,\n Optional,\n Sequence,\n Set,\n Tuple,\n Type,\n Union,\n)\n\nfrom pygments.lexer import Lexer\nfrom pygments.lexers import get_lexer_by_name, guess_lexer_for_filename\nfrom pygments.style import Style as PygmentsStyle\nfrom pygments.styles import get_style_by_name\nfrom pygments.token import (\n Comment,\n Error,\n Generic,\n Keyword,\n Name,\n Number,\n Operator,\n String,\n Token,\n Whitespace,\n)\nfrom pygments.util import ClassNotFound\n\nfrom rich.containers import Lines\nfrom rich.padding import Padding, PaddingDimensions\n\nfrom ._loop import loop_first\nfrom .cells import cell_len\nfrom .color import Color, blend_rgb\nfrom .console import Console, ConsoleOptions, JustifyMethod, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment, Segments\nfrom .style import Style, StyleType\nfrom .text import Text\n\nTokenType = Tuple[str, ...]\n\nWINDOWS = sys.platform == \"win32\"\nDEFAULT_THEME = \"monokai\"\n\n# The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py\n# A few modifications were made\n\nANSI_LIGHT: Dict[TokenType, Style] = {\n Token: Style(),\n Whitespace: Style(color=\"white\"),\n Comment: Style(dim=True),\n Comment.Preproc: Style(color=\"cyan\"),\n Keyword: Style(color=\"blue\"),\n Keyword.Type: Style(color=\"cyan\"),\n Operator.Word: Style(color=\"magenta\"),\n Name.Builtin: Style(color=\"cyan\"),\n Name.Function: Style(color=\"green\"),\n Name.Namespace: Style(color=\"cyan\", underline=True),\n Name.Class: Style(color=\"green\", underline=True),\n Name.E |
| 17 | read_file | {
"filepath": "rich/protocol.py"
} | {"status": "ok", "filepath": "rich/protocol.py", "content": "from typing import Any, cast, Set, TYPE_CHECKING\nfrom inspect import isclass\n\nif TYPE_CHECKING:\full{"status": "ok", "filepath": "rich/protocol.py", "content": "from typing import Any, cast, Set, TYPE_CHECKING\nfrom inspect import isclass\n\nif TYPE_CHECKING:\n from rich.console import RenderableType\n\n_GIBBERISH = \"\"\"aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf\"\"\"\n\n\ndef is_renderable(check_object: Any) -> bool:\n \"\"\"Check if an object may be rendered by Rich.\"\"\"\n return (\n isinstance(check_object, str)\n or hasattr(check_object, \"__rich__\")\n or hasattr(check_object, \"__rich_console__\")\n )\n\n\ndef rich_cast(renderable: object) -> \"RenderableType\":\n \"\"\"Cast an object to a renderable by calling __rich__ if present.\n\n Args:\n renderable (object): A potentially renderable object\n\n Returns:\n object: The result of recursively calling __rich__.\n \"\"\"\n from rich.console import RenderableType\n\n rich_visited_set: Set[type] = set() # Prevent potential infinite loop\n while hasattr(renderable, \"__rich__\") and not isclass(renderable):\n # Detect object which claim to have all the attributes\n if hasattr(renderable, _GIBBERISH):\n return repr(renderable)\n cast_method = getattr(renderable, \"__rich__\")\n renderable = cast_method()\n renderable_type = type(renderable)\n if renderable_type in rich_visited_set:\n break\n rich_visited_set.add(renderable_type)\n\n return cast(RenderableType, renderable)", "start_line": 1, "end_line": 42, "total_lines": 42, "is_truncated": false} |