fix: matplotlib SyntaxError in sandboxed Pyodide code execution (#26800)

The sandboxed Pyodide host (used when ENABLE_PYODIDE_FILE_PERSISTENCE is
disabled, the default) embeds its script in a String.raw template. The
matplotlib show() override was written with '\\t' escapes as if in a normal
string context, but String.raw preserves them verbatim, so the iframe's
script parser turns them into literal backslash-t characters in the
generated Python source. Pyodide then fails to compile any code that
triggers the matplotlib patch with "SyntaxError: unexpected character
after line continuation character", which is why matplotlib only worked
with the file persistence worker path enabled.

Use single '\t' escapes instead: String.raw keeps them as-is in the
script text and the sandbox's JS parser produces real tab indentation,
matching the working implementation in pyodide.worker.ts.

Fixes #26660
This commit is contained in:
Classic298
2026-07-24 05:34:26 +02:00
committed by GitHub
parent 0f8d12201c
commit b940cd529b

View File

@@ -116,13 +116,14 @@ const sandboxScript = String.raw`
'_old_show = matplotlib.pyplot.show',
'assert _old_show, "matplotlib.pyplot.show"',
'def show(*, block=None):',
'\\tbuf = BytesIO()',
'\\tmatplotlib.pyplot.savefig(buf, format="png")',
'\\tbuf.seek(0)',
'\\timg_str = base64.b64encode(buf.read()).decode("utf-8")',
'\\tmatplotlib.pyplot.clf()',
'\\tbuf.close()',
'\\tprint(f"data:image/png;base64,{img_str}")',
// String.raw keeps \t as-is; the sandbox's JS parser turns it into a real tab
'\tbuf = BytesIO()',
'\tmatplotlib.pyplot.savefig(buf, format="png")',
'\tbuf.seek(0)',
'\timg_str = base64.b64encode(buf.read()).decode("utf-8")',
'\tmatplotlib.pyplot.clf()',
'\tbuf.close()',
'\tprint(f"data:image/png;base64,{img_str}")',
'matplotlib.pyplot.show = show'
].join('\n'));
}