failed CONTEXT UNSUBMITTED agent_error · 35 tool calls · 258 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": "grep -rn \"import inspect\" rich | head -20"
} | {"status": "ok", "stdout": "rich/_inspect.py:1:import inspect\nrich/console.py:1:import inspect\nrich/pretty.py:4:import inspect\nrich/repr.py:1:import inspect\full{"status": "ok", "stdout": "rich/_inspect.py:1:import inspect\nrich/console.py:1:import inspect\nrich/pretty.py:4:import inspect\nrich/repr.py:1:import inspect\nrich/diagnose.py:4:from rich import inspect\nrich/traceback.py:1:import inspect\n", "exit_code": 0} |
| 2 | read_file | {
"filepath": "rich/logging.py",
"start_line": 1,
"end_line": 50
} | {"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 | {
"end_line": 297,
"filepath": "rich/logging.py",
"start_line": 51
} | {"status": "ok", "filepath": "rich/logging.py", "content": " \"\"\"\n\n KEYWORDS: ClassVar[Optional[List[str]]] = [\n \"GET\",\n \"POST\",\n \"HEAD\",\n \"PUT\"full{"status": "ok", "filepath": "rich/logging.py", "content": " \"\"\"\n\n KEYWORDS: ClassVar[Optional[List[str]]] = [\n \"GET\",\n \"POST\",\n \"HEAD\",\n \"PUT\",\n \"DELETE\",\n \"OPTIONS\",\n \"TRACE\",\n \"PATCH\",\n ]\n HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter\n\n def __init__(\n self,\n level: Union[int, str] = logging.NOTSET,\n console: Optional[Console] = None,\n *,\n show_time: bool = True,\n omit_repeated_times: bool = True,\n show_level: bool = True,\n show_path: bool = True,\n enable_link_path: bool = True,\n highlighter: Optional[Highlighter] = None,\n markup: bool = False,\n rich_tracebacks: bool = False,\n tracebacks_width: Optional[int] = None,\n tracebacks_code_width: Optional[int] = 88,\n tracebacks_extra_lines: int = 3,\n tracebacks_theme: Optional[str] = None,\n tracebacks_word_wrap: bool = True,\n tracebacks_show_locals: bool = False,\n tracebacks_suppress: Iterable[Union[str, ModuleType]] = (),\n tracebacks_max_frames: int = 100,\n locals_max_length: int = 10,\n locals_max_string: int = 80,\n log_time_format: Union[str, FormatTimeCallable] = \"[%x %X]\",\n keywords: Optional[List[str]] = None,\n ) -> None:\n super().__init__(level=level)\n self.console = console or get_console()\n self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()\n self._log_render = LogRender(\n show_time=show_time,\n show_level=show_level,\n show_path=show_path,\n 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_ |
| 4 | read_file | {
"end_line": 297,
"filepath": "rich/logging.py",
"start_line": 201
} | {"status": "ok", "filepath": "rich/logging.py", "content": "\n if self.keywords:\n message_text.highlight_words(self.keywords, \"logging.keyword\")\n\n return mfull{"status": "ok", "filepath": "rich/logging.py", "content": "\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://127.0.0.1:8080\")\n sleep(1)\n\n log.in |
| 5 | read_file | {
"end_line": 100,
"filepath": "rich/console.py",
"start_line": 1
} | {"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 = |
| 6 | read_file | {
"end_line": 300,
"filepath": "rich/console.py",
"start_line": 101
} | {"status": "ok", "filepath": "rich/console.py", "content": "\n_TERM_COLORS = {\n \"kitty\": ColorSystem.EIGHT_BIT,\n \"256color\": ColorSystem.EIGHT_BIT,\n \"16full{"status": "ok", "filepath": "rich/console.py", "content": "\n_TERM_COLORS = {\n \"kitty\": ColorSystem.EIGHT_BIT,\n \"256color\": ColorSystem.EIGHT_BIT,\n \"16color\": ColorSystem.STANDARD,\n}\n\n\nclass ConsoleDimensions(NamedTuple):\n \"\"\"Size of the terminal.\"\"\"\n\n width: int\n \"\"\"The width of the console in 'cells'.\"\"\"\n height: int\n \"\"\"The height of the console in lines.\"\"\"\n\n\n@dataclass\nclass ConsoleOptions:\n \"\"\"Options for __rich_console__ method.\"\"\"\n\n size: ConsoleDimensions\n \"\"\"Size of console.\"\"\"\n legacy_windows: bool\n \"\"\"legacy_windows: flag for legacy windows.\"\"\"\n min_width: int\n \"\"\"Minimum width of renderable.\"\"\"\n max_width: int\n \"\"\"Maximum width of renderable.\"\"\"\n is_terminal: bool\n \"\"\"True if the target is a terminal, otherwise False.\"\"\"\n encoding: str\n \"\"\"Encoding of terminal.\"\"\"\n max_height: int\n \"\"\"Height of container (starts as terminal)\"\"\"\n justify: Optional[JustifyMethod] = None\n \"\"\"Justify value override for renderable.\"\"\"\n overflow: Optional[OverflowMethod] = None\n \"\"\"Overflow value override for renderable.\"\"\"\n no_wrap: Optional[bool] = False\n \"\"\"Disable wrapping for text.\"\"\"\n highlight: Optional[bool] = None\n \"\"\"Highlight override for render_str.\"\"\"\n markup: Optional[bool] = None\n \"\"\"Enable markup when rendering strings.\"\"\"\n height: Optional[int] = None\n\n @property\n def ascii_only(self) -> bool:\n \"\"\"Check if renderables should use ascii only.\"\"\"\n return not self.encoding.startswith(\"utf\")\n\n def copy(self) -> \"ConsoleOptions\":\n \"\"\"Return a copy of the options.\n\n Returns:\n ConsoleOptions: a copy of self.\n \"\"\"\n options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)\n options.__dict__ = self.__dict__.copy()\n |
| 7 | run_command | {
"command": "grep -n \"def print(\" rich/console.py"
} | {"status": "ok", "stdout": "1648: def print(\n", "exit_code": 0}full{"status": "ok", "stdout": "1648: def print(\n", "exit_code": 0} |
| 8 | read_file | {
"end_line": 1700,
"filepath": "rich/console.py",
"start_line": 1640
} | {"status": "ok", "filepath": "rich/console.py", "content": " emoji=False,\n markup=False,\n no_wrap=True,\n overflow=\"ignore\",\n crop=False,\n end=end,\n )\n\full{"status": "ok", "filepath": "rich/console.py", "content": " emoji=False,\n markup=False,\n no_wrap=True,\n overflow=\"ignore\",\n crop=False,\n end=end,\n )\n\n def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n new_line_start: bool = False,\n ) -> None:\n \"\"\"Print to the console.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``N |
| 9 | run_command | {
"command": "grep -n \"def log(\" rich/console.py"
} | {"status": "ok", "stdout": "1936: def log(\n", "exit_code": 0}full{"status": "ok", "stdout": "1936: def log(\n", "exit_code": 0} |
| 10 | read_file | {
"end_line": 1980,
"filepath": "rich/console.py",
"start_line": 1930
} | {"status": "ok", "filepath": "rich/console.py", "content": " return frame.f_code.co_filename, frame.f_lineno, frame.f_locals\n else:\n # Fallback to the slower full{"status": "ok", "filepath": "rich/console.py", "content": " return frame.f_code.co_filename, frame.f_lineno, frame.f_locals\n else:\n # Fallback to the slower stack\n frame_info = inspect.stack()[offset]\n return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals\n\n def log(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n log_locals: bool = False,\n _stack_offset: int = 1,\n ) -> None:\n \"\"\"Log rich content to the terminal.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): One of \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.\n log_locals (bool, optional): Boolean to enable logging of locals where ``log()``\n was called. Defaults to False.\n _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.\n \"\"\"\n if not objects:\n objects = (NewLine(),)\n\n render_hooks |
| 11 | run_command | {
"command": "grep -n \"def input(\" rich/console.py"
} | {"status": "ok", "stdout": "2143: def input(\n", "exit_code": 0}full{"status": "ok", "stdout": "2143: def input(\n", "exit_code": 0} |
| 12 | read_file | {
"end_line": 2180,
"filepath": "rich/console.py",
"start_line": 2140
} | {"status": "ok", "filepath": "rich/console.py", "content": " rendered = \"\".join(output)\n return rendered\n\n def input(\n self,\n prompt: TextType = \"\",\n full{"status": "ok", "filepath": "rich/console.py", "content": " rendered = \"\".join(output)\n return rendered\n\n def input(\n self,\n prompt: TextType = \"\",\n *,\n markup: bool = True,\n emoji: bool = True,\n password: bool = False,\n stream: Optional[TextIO] = None,\n ) -> str:\n \"\"\"Displays a prompt and waits for input from the user. The prompt may contain color / style.\n\n It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded.\n\n Args:\n prompt (Union[str, Text]): Text to render in the prompt.\n markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.\n emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.\n password: (bool, optional): Hide typed text. Defaults to False.\n stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.\n\n Returns:\n str: Text read from stdin.\n \"\"\"\n if prompt:\n self.print(prompt, markup=markup, emoji=emoji, end=\"\")\n if password:\n result = getpass(\"\", stream=stream)\n else:\n if stream:\n result = stream.readline()\n else:\n result = input()\n return result\n\n def export_text(self, *, clear: bool = True, styles: bool = False) -> str:\n \"\"\"Generate text from console contents (requires record=True argument in constructor).\n\n Args:\n", "start_line": 2140, "end_line": 2180, "total_lines": 2684, "is_truncated": false} |
| 13 | run_command | {
"command": "grep -n \"_svg_hash\" rich/console.py"
} | {"status": "ok", "stdout": "2619:def _svg_hash(svg_main_code: str) -> str:\n", "exit_code": 0}full{"status": "ok", "stdout": "2619:def _svg_hash(svg_main_code: str) -> str:\n", "exit_code": 0} |
| 14 | read_file | {
"end_line": 2630,
"filepath": "rich/console.py",
"start_line": 2610
} | {"status": "ok", "filepath": "rich/console.py", "content": " clear=clear,\n code_format=code_format,\n font_aspect_ratio=font_aspect_ratio,\n unique_id=unique_ifull{"status": "ok", "filepath": "rich/console.py", "content": " clear=clear,\n code_format=code_format,\n font_aspect_ratio=font_aspect_ratio,\n unique_id=unique_id,\n )\n with open(path, \"w\", encoding=\"utf-8\") as write_file:\n write_file.write(svg)\n\n\ndef _svg_hash(svg_main_code: str) -> str:\n \"\"\"Returns a unique hash for the given SVG main code.\n\n Args:\n svg_main_code (str): The content we're going to inject in the SVG envelope.\n\n Returns:\n str: a hash of the given content\n \"\"\"\n return str(zlib.adler32(svg_main_code.encode()))\n\n\n", "start_line": 2610, "end_line": 2630, "total_lines": 2684, "is_truncated": false} |
| 15 | run_command | {
"command": "grep -n \"import configparser\" rich/theme.py"
} | {"status": "ok", "stdout": "1:import configparser\n", "exit_code": 0}full{"status": "ok", "stdout": "1:import configparser\n", "exit_code": 0} |
| 16 | read_file | {
"end_line": 100,
"filepath": "rich/theme.py",
"start_line": 1
} | {"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 |
| 17 | run_command | {
"command": "grep -n \"import logging\" rich/segment.py"
} | {"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 18 | run_command | {
"command": "grep -n \"logging\" rich/segment.py"
} | {"status": "ok", "stdout": "4:from logging import getLogger\n", "exit_code": 0}full{"status": "ok", "stdout": "4:from logging import getLogger\n", "exit_code": 0} |
| 19 | read_file | {
"end_line": 50,
"filepath": "rich/segment.py",
"start_line": 1
} | {"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", "start_line": 1, "end_line": 50, "total_lines": 783, "is_truncated": false} |
| 20 | run_command | {
"command": "grep -n \"import inspect\" rich/repr.py"
} | {"status": "ok", "stdout": "1:import inspect\n", "exit_code": 0}full{"status": "ok", "stdout": "1:import inspect\n", "exit_code": 0} |
| 21 | read_file | {
"end_line": 100,
"filepath": "rich/repr.py",
"start_line": 1
} | {"status": "ok", "filepath": "rich/repr.py", "content": "import inspect\nfrom functools import partial\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Lifull{"status": "ok", "filepath": "rich/repr.py", "content": "import inspect\nfrom functools import partial\nfrom typing import (\n Any,\n Callable,\n Iterable,\n List,\n Optional,\n Tuple,\n Type,\n TypeVar,\n Union,\n overload,\n)\n\nT = TypeVar(\"T\")\n\n\nResult = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]\nRichReprResult = Result\n\n\nclass ReprError(Exception):\n \"\"\"An error occurred when attempting to build a repr.\"\"\"\n\n\n@overload\ndef auto(cls: Optional[Type[T]]) -> Type[T]:\n ...\n\n\n@overload\ndef auto(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:\n ...\n\n\ndef auto(\n cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None\n) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:\n \"\"\"Class decorator to create __repr__ from __rich_repr__\"\"\"\n\n def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]:\n def auto_repr(self: T) -> str:\n \"\"\"Create repr string from __rich_repr__\"\"\"\n repr_str: List[str] = []\n append = repr_str.append\n\n angular: bool = getattr(self.__rich_repr__, \"angular\", False) # type: ignore[attr-defined]\n for arg in self.__rich_repr__(): # type: ignore[attr-defined]\n if isinstance(arg, tuple):\n if len(arg) == 1:\n append(repr(arg[0]))\n else:\n key, value, *default = arg\n if key is None:\n append(repr(value))\n else:\n if default and default[0] == value:\n continue\n append(f\"{key}={value!r}\")\n else:\n append(repr(arg))\n if angular:\n return f\"<{self.__class__.__name__} {' '.join(repr_str)}>\"\n else:\n |
| 22 | run_command | {
"command": "grep -n \"import inspect\" rich/protocol.py"
} | {"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 23 | run_command | {
"command": "grep -n \"inspect\" rich/protocol.py"
} | {"status": "ok", "stdout": "2:from inspect import isclass\n", "exit_code": 0}full{"status": "ok", "stdout": "2:from inspect import isclass\n", "exit_code": 0} |
| 24 | read_file | {
"end_line": 50,
"filepath": "rich/protocol.py",
"start_line": 1
} | {"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)\n", "start_line": 1, "end_line": 42, "total_lines": 42, "is_truncated": false} |
| 25 | run_command | {
"command": "grep -n \"import inspect\" rich/syntax.py"
} | {"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 1", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 26 | run_command | {
"command": "grep -n \"Console\" rich/syntax.py"
} | {"status": "ok", "stdout": "47:from .console import Console, ConsoleOptions, JustifyMethod, RenderResult\n599: def _get_number_styles(self, console: Console) ->full{"status": "ok", "stdout": "47:from .console import Console, ConsoleOptions, JustifyMethod, RenderResult\n599: def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:\n623: self, console: \"Console\", options: \"ConsoleOptions\"\n641: self, console: Console, options: ConsoleOptions\n651: console: Console,\n652: options: ConsoleOptions,\n956: from rich.console import Console\n958: console = Console(force_terminal=args.force_color, width=args.width)\n", "exit_code": 0} |
| 27 | read_file | {
"end_line": 60,
"filepath": "rich/syntax.py",
"start_line": 1
} | {"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", "start_line": 1, "end_line": 60, "total_lines": 985, "is_truncated": false} |
| 28 | edit_file | {
"filepath": "rich/logging.py",
"new_string": "from __future__ import annotations\n\nimport logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nimport os\nfrom types import ModuleType\nfrom typing import TYPE_CHECKING, ClassVar, Iterable, List, Optional, Type, Union\n\nif TYPE_CHECKING:\n from .console import Console, ConsoleRenderable\n from .highlighter import Highlighter\n from ._log_render import FormatTimeCallable\n\nfrom rich._null_file import NullFile\n\nfrom . import get_console\nfrom ._log_render import LogRender\nfrom .highlighter import ReprHighlighter\nfrom .text import Text\n",
"old_string": "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"
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -1,18 +1,23 @@\full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -1,18 +1,23 @@\n+from __future__ import annotations\n+\n import logging\n from datetime import datetime\n from logging import Handler, LogRecord\n-from pathlib import Path\n+import os\n from types import ModuleType\n-from typing import ClassVar, Iterable, List, Optional, Type, Union\n+from typing import TYPE_CHECKING, ClassVar, Iterable, List, Optional, Type, Union\n+\n+if TYPE_CHECKING:\n+ from .console import Console, ConsoleRenderable\n+ from .highlighter import Highlighter\n+ from ._log_render import FormatTimeCallable\n \n from rich._null_file import NullFile\n \n from . import get_console\n-from ._log_render import FormatTimeCallable, LogRender\n-from .console import Console, ConsoleRenderable\n-from .highlighter import Highlighter, ReprHighlighter\n+from ._log_render import LogRender\n+from .highlighter import ReprHighlighter\n from .text import Text\n-from .traceback import Traceback\n \n \n class RichHandler(Handler):\n", "is_truncated": false} |
| 29 | edit_file | {
"filepath": "rich/logging.py",
"new_string": " 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 from .traceback import Traceback\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 code_width=self.tracebacks_code_width,\n extra_lines=self.tracebacks_extra_lines,\n theme=self.tracebacks_theme,\n word_wrap=self.tracebacks_word_wrap,\n show_locals=self.tracebacks_show_locals,\n locals_max_length=self.locals_max_length,\n locals_max_string=self.locals_max_string,\n suppress=self.tracebacks_suppress,\n max_frames=self.tracebacks_max_frames,\n )\n message = record.getMessage()\n if self.formatter:\n record.message = record.getMessage()\n formatter = self.formatter\n if hasattr(formatter, \"usesTime\") and formatter.usesTime():\n record.asctime = formatter.formatTime(record, formatter.datefmt)\n message = formatter.formatMessage(record)\n",
"old_string": " 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 code_width=self.tracebacks_code_width,\n extra_lines=self.tracebacks_extra_lines,\n theme=self.tracebacks_theme,\n word_wrap=self.tracebacks_word_wrap,\n show_locals=self.tracebacks_show_locals,\n locals_max_length=self.locals_max_length,\n locals_max_string=self.locals_max_string,\n suppress=self.tracebacks_suppress,\n max_frames=self.tracebacks_max_frames,\n )\n message = record.getMessage()\n if self.formatter:\n record.message = record.getMessage()\n formatter = self.formatter\n if hasattr(formatter, \"usesTime\") and formatter.usesTime():\n record.asctime = formatter.formatTime(record, formatter.datefmt)\n message = formatter.formatMessage(record)\n"
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -143,6 +143,7 @full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -143,6 +143,7 @@\n and record.exc_info\n and record.exc_info != (None, None, None)\n ):\n+ from .traceback import Traceback\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", "is_truncated": false} |
| 30 | edit_file | {
"filepath": "rich/logging.py",
"new_string": " path = os.path.basename(record.pathname)\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",
"old_string": " 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"
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -227,7 +227,7 @full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -227,7 +227,7 @@\n Returns:\n ConsoleRenderable: Renderable to display log.\n \"\"\"\n- path = Path(record.pathname).name\n+ path = os.path.basename(record.pathname)\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", "is_truncated": false} |
| 31 | edit_file | {
"filepath": "rich/console.py",
"new_string": "import 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 html import escape\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",
"old_string": "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"
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1,4 +1,3 @@\n-full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1,4 +1,3 @@\n-import inspect\n import os\n import sys\n import threading\n@@ -7,9 +6,7 @@\n from dataclasses import dataclass, field\n from datetime import datetime\n from functools import wraps\n-from getpass import getpass\n from html import escape\n-from inspect import isclass\n from itertools import islice\n from math import ceil\n from time import monotonic\n", "is_truncated": false} |
| 32 | edit_file | {
"filepath": "rich/console.py",
"new_string": " def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n new_line_start: bool = False,\n ) -> None:\n \"\"\"Print to the console.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\n width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.\n crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.\n soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for\n Console default. Defaults to ``None``.\n new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.\n \"\"\"\n if not objects:\n objects = (NewLine(),)\n\n if soft_wrap is None:\n soft_wrap = self.soft_wrap\n if soft_wrap:\n if no_wrap is None:\n no_wrap = True\n if overflow is None:\n overflow = \"ignore\"\n crop = False\n render_hooks = self._render_hooks[:]\n with self:\n renderables = self._collect_renderables(\n objects,\n sep,\n",
"old_string": " def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n new_line_start: bool = False,\n ) -> None:\n \"\"\"Print to the console.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\\\\\\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): Justify method: \"default\", \"lef | {"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"}full{"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"} |
| 33 | read_file | {
"end_line": 1660,
"filepath": "rich/console.py",
"start_line": 1640
} | {"status": "ok", "filepath": "rich/console.py", "content": " overflow=\"ignore\",\n crop=False,\n end=end,\n )\n\n def print(\n self,\n *objects: Any,\n sep: stfull{"status": "ok", "filepath": "rich/console.py", "content": " overflow=\"ignore\",\n crop=False,\n end=end,\n )\n\n def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n", "start_line": 1640, "end_line": 1660, "total_lines": 2681, "is_truncated": false} |
| 34 | edit_file | {
"filepath": "rich/console.py",
"new_string": " def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n new_line_start: bool = False,\n ) -> None:\n \"\"\"Print to the console.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\n width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.\n crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.\n soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for\n Console default. Defaults to ``None``.\n new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.\n \"\"\"\n from .pretty import Pretty\n if not objects:\n objects = (NewLine(),)\n",
"old_string": " def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n new_line_start: bool = False,\n ) -> None:\n \"\"\"Print to the console.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\\\\\\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to `` | {"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"}full{"status": "error", "error_type": "FileEditError", "error_message": "old_string not found in file (tried exact, flexible and regex matching)"} |
| 35 | read_file | {
"end_line": 1710,
"filepath": "rich/console.py",
"start_line": 1640
} | {"status": "ok", "filepath": "rich/console.py", "content": " overflow=\"ignore\",\n crop=False,\n end=end,\n )\n\n def print(\n self,\n *objects: Any,\n sep: stfull{"status": "ok", "filepath": "rich/console.py", "content": " overflow=\"ignore\",\n crop=False,\n end=end,\n )\n\n def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Union[str, Style]] = None,\n justify: Optional[JustifyMethod] = None,\n overflow: Optional[OverflowMethod] = None,\n no_wrap: Optional[bool] = None,\n emoji: Optional[bool] = None,\n markup: Optional[bool] = None,\n highlight: Optional[bool] = None,\n width: Optional[int] = None,\n height: Optional[int] = None,\n crop: bool = True,\n soft_wrap: Optional[bool] = None,\n new_line_start: bool = False,\n ) -> None:\n \"\"\"Print to the console.\n\n Args:\n objects (positional args): Objects to log to the terminal.\n sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\n width (Optional[int], optional): Width of output, or ``None` |
diff --git a/rich/console.py b/rich/console.py
index ad92d529..3804c1a6 100644
--- a/rich/console.py
+++ b/rich/console.py
@@ -1,4 +1,3 @@
-import inspect
import os
import sys
import threading
@@ -7,9 +6,7 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime
from functools import wraps
-from getpass import getpass
from html import escape
-from inspect import isclass
from itertools import islice
from math import ceil
from time import monotonic
diff --git a/rich/logging.py b/rich/logging.py
index c3e7a5f6..9a13b8b7 100644
--- a/rich/logging.py
+++ b/rich/logging.py
@@ -1,18 +1,23 @@
+from __future__ import annotations
+
import logging
from datetime import datetime
from logging import Handler, LogRecord
-from pathlib import Path
+import os
from types import ModuleType
-from typing import ClassVar, Iterable, List, Optional, Type, Union
+from typing import TYPE_CHECKING, ClassVar, Iterable, List, Optional, Type, Union
+
+if TYPE_CHECKING:
+ from .console import Console, ConsoleRenderable
+ from .highlighter import Highlighter
+ from ._log_render import FormatTimeCallable
from rich._null_file import NullFile
from . import get_console
-from ._log_render import FormatTimeCallable, LogRender
-from .console import Console, ConsoleRenderable
-from .highlighter import Highlighter, ReprHighlighter
+from ._log_render import LogRender
+from .highlighter import ReprHighlighter
from .text import Text
-from .traceback import Traceback
class RichHandler(Handler):
@@ -138,6 +143,7 @@ class RichHandler(Handler):
and record.exc_info
and record.exc_info != (None, None, None)
):
+ from .traceback import Traceback
exc_type, exc_value, exc_traceback = record.exc_info
assert exc_type is not None
assert exc_value is not None
@@ -221,7 +227,7 @@ class RichHandler(Handler):
Returns:
ConsoleRenderable: Renderable to display log.
"""
- path = Path(record.pathname).name
+ path = os.path.basename(record.pathname)
level = self.get_level_text(record)
time_format = None if self.formatter is None else self.formatter.datefmt
log_time = datetime.fromtimestamp(record.created)
==================================== ERRORS ====================================
_______________________ ERROR collecting test_console.py _______________________
tests/test_console.py:15: in <module>
from rich.console import (
rich/console.py:584: in <module>
class Console:
rich/console.py:1901: in Console
currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,
E NameError: name 'inspect' is not defined. Did you forget to import 'inspect'?
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
1 error in 0.33s