From 4e4b324246e8084fe87abd559677f1a180b138f2 Mon Sep 17 00:00:00 2001 From: Classic298 <27028174+Classic298@users.noreply.github.com> Date: Thu, 24 Sep 2026 05:51:39 +0200 Subject: [PATCH] fix: skip the pyodide plt.show patch when matplotlib is not loaded (#30381) Any Python code that only mentioned "matplotlib" (a comment, a string, or an importlib.util.find_spec("matplotlib") check) failed with ModuleNotFoundError before a single line of it ran. The plt.show() patch was applied on a plain substring match, but matplotlib is only installed when the code actually imports it, so the patch's own import crashed the run. The user's try/except could not catch it, because their code never started. The same thing broke the code editor's Python formatter on any code that imports matplotlib, since that run only installs black. The patch now also requires matplotlib to be present in the runtime's loaded packages, in both the worker and the sandboxed iframe host. Real matplotlib code still gets inline PNG output from plt.show(), and code that merely mentions matplotlib runs unchanged. Gating on the callers' import regex instead was also tested and still fails the formatter case, because there the code containing the import sits inside a string while only black is installed. Fixes #29894 --- src/lib/pyodide/pyodideSandboxHost.ts | 2 +- src/lib/workers/pyodide.worker.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/pyodide/pyodideSandboxHost.ts b/src/lib/pyodide/pyodideSandboxHost.ts index 2ba1ca2b27..b99ac0fc71 100644 --- a/src/lib/pyodide/pyodideSandboxHost.ts +++ b/src/lib/pyodide/pyodideSandboxHost.ts @@ -134,7 +134,7 @@ const sandboxScript = String.raw` let result = null; if (files && files.length > 0) upload(files); try { - if (code.includes('matplotlib')) await patchMatplotlib(); + if (code.includes('matplotlib') && 'matplotlib' in pyodide.loadedPackages) await patchMatplotlib(); result = clean(await pyodide.runPythonAsync(code)); } catch (error) { stderr = error && error.message ? error.message : String(error); diff --git a/src/lib/workers/pyodide.worker.ts b/src/lib/workers/pyodide.worker.ts index cdbd9006ec..4eb3ee7a31 100644 --- a/src/lib/workers/pyodide.worker.ts +++ b/src/lib/workers/pyodide.worker.ts @@ -191,7 +191,7 @@ async function executeCode( try { // check if matplotlib is imported in the code - if (code.includes('matplotlib')) { + if (code.includes('matplotlib') && 'matplotlib' in self.pyodide.loadedPackages) { // Override plt.show() to return base64 image await self.pyodide.runPythonAsync(`import base64 import os