failed WRONG_FIX UNSUBMITTED wrong_fix_unsubmitted(budget) · 37 tool calls · 310 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", "exit_code": 0} |
| 2-3 ×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 |
| 4 | run_command | {
"command": "grep -n \"Traceback.from_exception\" rich/logging.py"
} | {"status": "ok", "stdout": "144: traceback = Traceback.from_exception(\n", "exit_code": 0}full{"status": "ok", "stdout": "144: traceback = Traceback.from_exception(\n", "exit_code": 0} |
| 5 | read_file | {
"filepath": "rich/logging.py",
"start_line": 1,
"end_line": 20
} | {"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", "start_line": 1, "end_line": 20, "total_lines": 297, "is_truncated": false} |
| 6 | read_file | {
"end_line": 297,
"filepath": "rich/logging.py",
"start_line": 151
} | {"status": "ok", "filepath": "rich/logging.py", "content": " theme=self.tracebacks_theme,\n word_wrap=self.tracebacks_word_wrap,\n show_locals=self.tracebacks_sfull{"status": "ok", "filepath": "rich/logging.py", "content": " 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\n message_renderable = self.render_message(record, message)\n log_renderable = self.render(\n record=record, traceback=traceback, message_renderable=message_renderable\n )\n if isinstance(self.console.file, NullFile):\n # Handles pythonw, where stdout/stderr are null, and we return NullFile\n # instance from Console.file. In this case, we still want to make a log record\n # even though we won't be writing anything to a file.\n self.handleError(record)\n else:\n try:\n self.console.print(log_renderable)\n except Exception:\n self.handleError(record)\n\n def render_message(self, record: LogRecord, message: str) -> \"ConsoleRenderable\":\n \"\"\"Render message text in to Text.\n\n Args:\n record (LogRecord): logging Record.\n message (str): String containing log message.\n\n Returns:\n ConsoleRenderable: Renderable to display log message.\n \"\"\"\n use_markup = getattr(record, \"markup\", self.markup)\n message_ |
| 7 | read_file | {
"end_line": 15,
"filepath": "rich/logging.py",
"start_line": 1
} | {"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", "start_line": 1, "end_line": 15, "total_lines": 297, "is_truncated": false} |
| 8 | edit_file | {
"filepath": "rich/logging.py",
"new_string": "from __future__ import annotations\n\nimport logging\nimport os\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom types import ModuleType\nfrom typing import TYPE_CHECKING, ClassVar, Iterable, List, Optional, Type, Union\n\nif TYPE_CHECKING:\n from pathlib import Path\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",
"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"
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -1,16 +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,16 +1,23 @@\n+from __future__ import annotations\n+\n import logging\n+import os\n from datetime import datetime\n from logging import Handler, LogRecord\n-from pathlib import Path\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 pathlib import Path\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", "is_truncated": false} |
| 9 | 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(",
"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("
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -145,6 +145,7 @full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -145,6 +145,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} |
| 10 | edit_file | {
"filepath": "rich/logging.py",
"new_string": "from .text import Text\n# Remove Traceback from here as it is deferred in emit()\n",
"old_string": "from .text import Text\nfrom .traceback import Traceback"
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -19,7 +19,8 @@\full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -19,7 +19,8 @@\n from ._log_render import LogRender\n from .highlighter import ReprHighlighter\n from .text import Text\n-from .traceback import Traceback\n+# Remove Traceback from here as it is deferred in emit()\n+\n \n \n class RichHandler(Handler):\n", "is_truncated": false} |
| 11 | edit_file | {
"filepath": "rich/logging.py",
"new_string": " 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=os.path.basename(record.pathname),\n line_no=record.lineno,\n link_path=record.pathname if self.enable_link_path else None,\n )",
"old_string": " 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 )"
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -241,7 +241,7 @full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -241,7 +241,7 @@\n log_time=log_time,\n time_format=time_format,\n level=level,\n- path=path,\n+ path=os.path.basename(record.pathname),\n line_no=record.lineno,\n link_path=record.pathname if self.enable_link_path else None,\n )\n", "is_truncated": false} |
| 12 | edit_file | {
"filepath": "rich/logging.py",
"new_string": " log_time = datetime.fromtimestamp(record.created)\n\n log_renderable = self._log_render(",
"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\n log_renderable = self._log_render("
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -230,9 +230,6 @full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -230,9 +230,6 @@\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", "is_truncated": false} |
| 13 | edit_file | {
"filepath": "rich/logging.py",
"new_string": " log_time = datetime.fromtimestamp(record.created)\n level = self.get_level_text(record)\n time_format = None if self.formatter is None else self.formatter.datefmt\n\n log_renderable = self._log_render(",
"old_string": " log_time = datetime.fromtimestamp(record.created)\n\n log_renderable = self._log_render("
} | {"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -231,6 +231,8 @full{"status": "ok", "filepath": "rich/logging.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/logging.py\n+++ b/rich/logging.py\n@@ -231,6 +231,8 @@\n ConsoleRenderable: Renderable to display log.\n \"\"\"\n log_time = datetime.fromtimestamp(record.created)\n+ level = self.get_level_text(record)\n+ time_format = None if self.formatter is None else self.formatter.datefmt\n \n log_renderable = self._log_render(\n self.console,\n", "is_truncated": false} |
| 14 | 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 = |
| 15 | run_command | {
"command": "grep -n \"isclass\" rich/console.py"
} | {"status": "ok", "stdout": "12:from inspect import isclass\n1324: if hasattr(renderable, \"__rich_console__\") and not isclass(renderable):\n", "exit_code": 0}full{"status": "ok", "stdout": "12:from inspect import isclass\n1324: if hasattr(renderable, \"__rich_console__\") and not isclass(renderable):\n", "exit_code": 0} |
| 16 | run_command | {
"command": "grep -n \"currentframe\" rich/console.py"
} | {"status": "ok", "stdout": "1904: currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,\n1910: currentframe (Callable[[], Optional[FrameType]]full{"status": "ok", "stdout": "1904: currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,\n1910: currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to\n1911: retrieve the current frame. Defaults to ``inspect.currentframe``.\n1923: frame = currentframe()\n1925: # Use the faster currentframe where implemented\n", "exit_code": 0} |
| 17 | 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 getpass import getpass\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 (",
"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 ("
} | {"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@@ -9,7 +8,6 @@\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} |
| 18 | edit_file | {
"filepath": "rich/console.py",
"new_string": " if hasattr(renderable, \"__rich_console__\") and not isinstance(renderable, type):",
"old_string": " if hasattr(renderable, \"__rich_console__\") and not isclass(renderable):"
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1319,7 +1319,7full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1319,7 +1319,7 @@\n render_iterable: RenderResult\n \n renderable = rich_cast(renderable)\n- if hasattr(renderable, \"__rich_console__\") and not isclass(renderable):\n+ if hasattr(renderable, \"__rich_console__\") and not isinstance(renderable, type):\n render_iterable = renderable.__rich_console__(self, _options)\n elif isinstance(renderable, str):\n text_renderable = self.render_str(\n", "is_truncated": false} |
| 19 | edit_file | {
"filepath": "rich/console.py",
"new_string": " def log(\n self,\n message: Any,\n *,\n log_locals: bool = False,\n style: Optional[StyleType] = None,\n ) -> None:\n \"\"\"Log a message to the console.\n\n Args:\n message (Any): The message to log.\n log_locals (bool): Whether to log local variables. Defaults to False.\n style (StyleType, optional): The style to use for the message. Defaults to None.\n \"\"\"\n if log_locals:\n from .scope import render_scope\n message = render_scope(message)\n\n self.print(message, style=style)",
"old_string": " def log(\n self,\n message: Any,\n *,\n log_locals: bool = False,\n style: Optional[StyleType] = None,\n ) -> None:\n \"\"\"Log a message to the console.\n\n Args:\n message (Any): The message to log.\n log_locals (bool): Whether to log local variables. Defaults to False.\n style (StyleType, optional): The style to use for the message. Defaults to None.\n \"\"\"\n if log_locals:\n message = render_scope(message)\n\n self.print(message, style=style)"
} | {"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)"} |
| 20 | run_command | {
"command": "grep -n \"def log(\" rich/console.py"
} | {"status": "ok", "stdout": "1934: def log(\n", "exit_code": 0}full{"status": "ok", "stdout": "1934: def log(\n", "exit_code": 0} |
| 21 | read_file | {
"end_line": 1950,
"filepath": "rich/console.py",
"start_line": 1934
} | {"status": "ok", "filepath": "rich/console.py", "content": " def log(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Unionfull{"status": "ok", "filepath": "rich/console.py", "content": " 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", "start_line": 1934, "end_line": 1950, "total_lines": 2682, "is_truncated": false} |
| 22 | read_file | {
"end_line": 1970,
"filepath": "rich/console.py",
"start_line": 1951
} | {"status": "ok", "filepath": "rich/console.py", "content": " sep (str, optional): String to write between print data. Defaults to \" \".\n end (str, optional): full{"status": "ok", "filepath": "rich/console.py", "content": " 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 = self._render_hooks[:]\n\n with self:\n renderables = self._collect_renderables(\n objects,\n sep,\n", "start_line": 1951, "end_line": 1970, "total_lines": 2682, "is_truncated": false} |
| 23 | read_file | {
"end_line": 2000,
"filepath": "rich/console.py",
"start_line": 1971
} | {"status": "ok", "filepath": "rich/console.py", "content": " end,\n justify=justify,\n emoji=emoji,\n markup=markup,\n highlight=highlight,\n )\n if style is nofull{"status": "ok", "filepath": "rich/console.py", "content": " end,\n justify=justify,\n emoji=emoji,\n markup=markup,\n highlight=highlight,\n )\n if style is not None:\n renderables = [Styled(renderable, style) for renderable in renderables]\n\n filename, line_no, locals = self._caller_frame_info(_stack_offset)\n link_path = None if filename.startswith(\"<\") else os.path.abspath(filename)\n path = filename.rpartition(os.sep)[-1]\n if log_locals:\n locals_map = {\n key: value\n for key, value in locals.items()\n if not key.startswith(\"__\")\n }\n renderables.append(render_scope(locals_map, title=\"[i]locals\"))\n\n renderables = [\n self._log_render(\n self,\n renderables,\n log_time=self.get_datetime(),\n path=path,\n line_no=line_no,\n link_path=link_path,\n )\n ]\n", "start_line": 1971, "end_line": 2000, "total_lines": 2682, "is_truncated": false} |
| 24 | edit_file | {
"filepath": "rich/console.py",
"new_string": " if log_locals:\n from .scope import render_scope\n locals_map = {\n key: value\n for key, value in locals.items()\n if not key.startswith(\"__\")\n }\n renderables.append(render_scope(locals_map, title=\"[i]locals\"))",
"old_string": " if log_locals:\n locals_map = {\n key: value\n for key, value in locals.items()\n if not key.startswith(\"__\")\n }\n renderables.append(render_scope(locals_map, title=\"[i]locals\"))"
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1981,6 +1981,7full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1981,6 +1981,7 @@\n link_path = None if filename.startswith(\"<\") else os.path.abspath(filename)\n path = filename.rpartition(os.sep)[-1]\n if log_locals:\n+ from .scope import render_scope\n locals_map = {\n key: value\n for key, value in locals.items()\n", "is_truncated": false} |
| 25 | edit_file | {
"filepath": "rich/console.py",
"new_string": "from .pretty import Pretty\nfrom .protocol import rich_cast\nfrom .region import Region\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",
"old_string": "from .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"
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -48,10 +48,9 @@full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -48,10 +48,9 @@\n from .markup import render as render_markup\n from .measure import Measurement, measure_renderables\n from .pager import Pager, SystemPager\n-from .pretty import Pretty, is_expandable\n+from .pretty import Pretty\n from .protocol import rich_cast\n from .region import Region\n-from .scope import render_scope\n from .screen import Screen\n from .segment import Segment\n from .style import Style, StyleType\n", "is_truncated": false} |
| 26 | run_command | {
"command": "grep -n \"is_expandable\" rich/console.py"
} | {"status": "ok", "stdout": "1568: elif is_expandable(renderable):\n", "exit_code": 0}full{"status": "ok", "stdout": "1568: elif is_expandable(renderable):\n", "exit_code": 0} |
| 27 | read_file | {
"end_line": 1580,
"filepath": "rich/console.py",
"start_line": 1550
} | {"status": "ok", "filepath": "rich/console.py", "content": "\n for renderable in objects:\n renderable = rich_cast(renderable)\n if isinstance(renderable, str):full{"status": "ok", "filepath": "rich/console.py", "content": "\n for renderable in objects:\n renderable = rich_cast(renderable)\n if isinstance(renderable, str):\n append_text(\n self.render_str(\n renderable,\n emoji=emoji,\n markup=markup,\n highlight=highlight,\n highlighter=_highlighter,\n )\n )\n elif isinstance(renderable, Text):\n append_text(renderable)\n elif isinstance(renderable, ConsoleRenderable):\n check_text()\n append(renderable)\n elif is_expandable(renderable):\n check_text()\n append(Pretty(renderable, highlighter=_highlighter))\n else:\n append_text(_highlighter(str(renderable)))\n\n check_text()\n\n if self.style is not None:\n style = self.get_style(self.style)\n renderables = [Styled(renderable, style) for renderable in renderables]\n\n return renderables\n", "start_line": 1550, "end_line": 1580, "total_lines": 2682, "is_truncated": false} |
| 28 | edit_file | {
"filepath": "rich/console.py",
"new_string": " elif is_expandable(renderable):\n from .pretty import is_expandable\n check_text()\n append(Pretty(renderable, highlighter=_highlighter))",
"old_string": " elif is_expandable(renderable):\n check_text()\n append(Pretty(renderable, highlighter=_highlighter))"
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1566,6 +1566,7full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1566,6 +1566,7 @@\n check_text()\n append(renderable)\n elif is_expandable(renderable):\n+ from .pretty import is_expandable\n check_text()\n append(Pretty(renderable, highlighter=_highlighter))\n else:\n", "is_truncated": false} |
| 29 | edit_file | {
"filepath": "rich/console.py",
"new_string": " elif is_expandable(renderable):\n check_text()\n append(Pretty(renderable, highlighter=_highlighter))",
"old_string": " elif is_expandable(renderable):\n from .pretty import is_expandable\n check_text()\n append(Pretty(renderable, highlighter=_highlighter))"
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1566,7 +1566,6full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1566,7 +1566,6 @@\n check_text()\n append(renderable)\n elif is_expandable(renderable):\n- from .pretty import is_expandable\n check_text()\n append(Pretty(renderable, highlighter=_highlighter))\n else:\n", "is_truncated": false} |
| 30 | run_command | {
"command": "grep -n \"def print(\" rich/console.py"
} | {"status": "ok", "stdout": "1645: def print(\n", "exit_code": 0}full{"status": "ok", "stdout": "1645: def print(\n", "exit_code": 0} |
| 31 | read_file | {
"end_line": 1700,
"filepath": "rich/console.py",
"start_line": 1645
} | {"status": "ok", "filepath": "rich/console.py", "content": " def print(\n self,\n *objects: Any,\n sep: str = \" \",\n end: str = \"\\n\",\n style: Optional[Unifull{"status": "ok", "filepath": "rich/console.py", "content": " 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 out |
| 32 | run_command | {
"command": "grep -n \"def input(\" rich/console.py"
} | {"status": "ok", "stdout": "2141: def input(\n", "exit_code": 0}full{"status": "ok", "stdout": "2141: def input(\n", "exit_code": 0} |
| 33 | read_file | {
"end_line": 2170,
"filepath": "rich/console.py",
"start_line": 2141
} | {"status": "ok", "filepath": "rich/console.py", "content": " def input(\n self,\n prompt: TextType = \"\",\n *,\n markup: bool = True,\n emoji: bool = True,\n pfull{"status": "ok", "filepath": "rich/console.py", "content": " 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", "start_line": 2141, "end_line": 2170, "total_lines": 2682, "is_truncated": false} |
| 34 | edit_file | {
"filepath": "rich/console.py",
"new_string": " if password:\n from getpass import getpass\n result = getpass(\"\", stream=stream)\n else:",
"old_string": " if password:\n result = getpass(\"\", stream=stream)\n else:"
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -2164,6 +2164,7full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -2164,6 +2164,7 @@\n if prompt:\n self.print(prompt, markup=markup, emoji=emoji, end=\"\")\n if password:\n+ from getpass import getpass\n result = getpass(\"\", stream=stream)\n else:\n if stream:\n", "is_truncated": false} |
| 35 | edit_file | {
"filepath": "rich/console.py",
"new_string": "import os\nimport sys\nimport threading\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 (",
"old_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 getpass import getpass\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 ("
} | {"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1,12 +1,10 @@\full{"status": "ok", "filepath": "rich/console.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/rich/console.py\n+++ b/rich/console.py\n@@ -1,12 +1,10 @@\n import os\n import sys\n import threading\n-import zlib\n from abc import ABC, abstractmethod\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 itertools import islice\n from math import ceil\n", "is_truncated": false} |
| 36 | run_command | {
"command": "grep -n \"zlib\" rich/console.py"
} | {"status": "ok", "stdout": "2448: zlib.adler32(\n2625: return str(zlib.adler32(svg_main_code.encode()))\n", "exit_code": 0}full{"status": "ok", "stdout": "2448: zlib.adler32(\n2625: return str(zlib.adler32(svg_main_code.encode()))\n", "exit_code": 0} |
| 37 | read_file | {
"end_line": 2460,
"filepath": "rich/console.py",
"start_line": 2430
} | {"status": "ok", "filepath": "rich/console.py", "content": "\n tag_attribs = \" \".join(\n f'{k.lstrip(\"_\").replace(\"_\", \"-\")}=\"{stringify(v)}\"'\n for kfull{"status": "ok", "filepath": "rich/console.py", "content": "\n tag_attribs = \" \".join(\n f'{k.lstrip(\"_\").replace(\"_\", \"-\")}=\"{stringify(v)}\"'\n for k, v in attribs.items()\n )\n return (\n f\"<{name} {tag_attribs}>{content}</{name}>\"\n if content\n else f\"<{name} {tag_attribs}/>\"\n )\n\n with self._record_buffer_lock:\n segments = list(Segment.filter_control(self._record_buffer))\n if clear:\n self._record_buffer.clear()\n\n if unique_id is None:\n unique_id = \"terminal-\" + str(\n zlib.adler32(\n (\"\".join(repr(segment) for segment in segments)).encode(\n \"utf-8\",\n \"ignore\",\n )\n + title.encode(\"utf-8\", \"ignore\")\n )\n )\n y = 0\n for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)):\n x = 0\n for text, style, _control in line:\n style = style or Style()\n", "start_line": 2430, "end_line": 2460, "total_lines": 2681, "is_truncated": false} |
diff --git a/rich/console.py b/rich/console.py
index ad92d529..6bc9b78d 100644
--- a/rich/console.py
+++ b/rich/console.py
@@ -1,15 +1,11 @@
-import inspect
import os
import sys
import threading
-import zlib
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
@@ -50,10 +46,9 @@ from .highlighter import NullHighlighter, ReprHighlighter
from .markup import render as render_markup
from .measure import Measurement, measure_renderables
from .pager import Pager, SystemPager
-from .pretty import Pretty, is_expandable
+from .pretty import Pretty
from .protocol import rich_cast
from .region import Region
-from .scope import render_scope
from .screen import Screen
from .segment import Segment
from .style import Style, StyleType
@@ -1321,7 +1316,7 @@ class Console:
render_iterable: RenderResult
renderable = rich_cast(renderable)
- if hasattr(renderable, "__rich_console__") and not isclass(renderable):
+ if hasattr(renderable, "__rich_console__") and not isinstance(renderable, type):
render_iterable = renderable.__rich_console__(self, _options)
elif isinstance(renderable, str):
text_renderable = self.render_str(
@@ -1983,6 +1978,7 @@ class Console:
link_path = None if filename.startswith("<") else os.path.abspath(filename)
path = filename.rpartition(os.sep)[-1]
if log_locals:
+ from .scope import render_scope
locals_map = {
key: value
for key, value in locals.items()
@@ -2166,6 +2162,7 @@ class Console:
if prompt:
self.print(prompt, markup=markup, emoji=emoji, end="")
if password:
+ from getpass import getpass
result = getpass("", stream=stream)
else:
if stream:
diff --git a/rich/logging.py b/rich/logging.py
index c3e7a5f6..a2158838 100644
--- a/rich/logging.py
+++ b/rich/logging.py
@@ -1,18 +1,26 @@
+from __future__ import annotations
+
import logging
+import os
from datetime import datetime
from logging import Handler, LogRecord
-from pathlib import Path
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 pathlib import Path
+ 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
+# Remove Traceback from here as it is deferred in emit()
+
class RichHandler(Handler):
@@ -138,6 +146,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,10 +230,9 @@ class RichHandler(Handler):
Returns:
ConsoleRenderable: Renderable to display log.
"""
- path = Path(record.pathname).name
+ log_time = datetime.fromtimestamp(record.created)
level = self.get_level_text(record)
time_format = None if self.formatter is None else self.formatter.datefmt
- log_time = datetime.fromtimestamp(record.created)
log_renderable = self._log_render(
self.console,
@@ -232,7 +240,7 @@ class RichHandler(Handler):
log_time=log_time,
time_format=time_format,
level=level,
- path=path,
+ path=os.path.basename(record.pathname),
line_no=record.lineno,
link_path=record.pathname if self.enable_link_path else None,
)
==================================== ERRORS ====================================
_______________________ ERROR collecting test_console.py _______________________
tests/test_console.py:15: in <module>
from rich.console import (
rich/console.py:582: in <module>
class Console:
rich/console.py:1899: 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.30s