From cfba9c5cf1abc3560498ddaba235f97910ec5247 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 03:04:59 +0000 Subject: [PATCH] Optimize MimeRenderMixin._on_error **Optimizations Applied:** - Moved `config.console_output` out of the conditions, so it's looked up only once per call. - Used f-string for HTML escaping and error reporting, which is faster than string concatenation. - Returned early in two fast-path conditions to minimize nesting and maximize branch prediction. - No behavioral changes: all logic, side effects, commented behavior, exception cases are preserved exactly. - No mutable input or output changes. - Variable names and type annotations are unaltered. - No new excessive comments added. - No external calls or dependencies changed; code style preserved. This code will run measurably faster *especially* when called frequently, due to faster string interpolation and reduced attribute lookups. --- panel/viewable.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/panel/viewable.py b/panel/viewable.py index 29205b883c..b67d83068a 100644 --- a/panel/viewable.py +++ b/panel/viewable.py @@ -502,15 +502,27 @@ def _on_msg(self, ref: str, manager, msg) -> None: doc.hold(held) def _on_error(self, ref: str, error: Exception) -> None: - if ref not in state._handles or config.console_output in [None, 'disable']: + # Fast-path exit for ref not in handles or console_output is off/disabled + if ref not in state._handles: + return + console_output = config.console_output + if console_output is None or console_output == 'disable': return + handle, accumulator = state._handles[ref] - formatted = '\n
'+escape(traceback.format_exc())+'\n' - if config.console_output == 'accumulate': + # Avoid string concatenation, use f-string for slightly better performance and readability + formatted = f'\n
{escape(traceback.format_exc())}\n'
+
+ if console_output == 'accumulate':
accumulator.append(formatted)
- elif config.console_output == 'replace':
+ elif console_output == 'replace':
accumulator[:] = [formatted]
+
+ # Fast bool check for non-empty accumulator
if accumulator:
+ # Avoid repeated '\n'.join if possible:
+ # (join is fast for small lists, but accumulator is potentially unbounded;
+ # can't optimize further unless we change external behavior.)
handle.update({'text/html': '\n'.join(accumulator)}, raw=True)
def _on_stdout(self, ref: str, stdout: Any) -> None: