66from functools import partial
77from io import StringIO
88from typing import Any
9+ from uuid import uuid4
910
1011from markdown .core import Markdown
1112
@@ -24,12 +25,11 @@ def buffer_print(buffer: StringIO, *text: str, end: str = "\n", **kwargs: Any) -
2425 buffer .write (" " .join (text ) + end )
2526
2627
27- def run_python (code : str , html : bool , ** extra : str ) -> str :
28+ def run_python (code : str , ** extra : str ) -> str :
2829 """Run Python code using `exec` and return its output.
2930
3031 Parameters:
3132 code: The code to execute.
32- html: Whether the output is HTML.
3333 **extra: Extra options passed to the traceback code block in case of errors.
3434
3535 Returns:
@@ -46,12 +46,8 @@ def run_python(code: str, html: bool, **extra: str) -> str:
4646 if frame .filename == "<string>" :
4747 frame .filename = "<executed code block>"
4848 frame ._line = code .split ("\n " )[frame .lineno - 1 ] # type: ignore[attr-defined,operator] # noqa: WPS437
49- output = code_block ("python" , "" .join (trace .format ()), ** extra )
50- else :
51- output = buffer .getvalue ()
52- if html :
53- output = f'<div markdown="0">{ str (output )} </div>'
54- return output
49+ return code_block ("python" , "" .join (trace .format ()), ** extra )
50+ return buffer .getvalue ()
5551
5652
5753def format_python ( # noqa: WPS231
@@ -77,7 +73,12 @@ def format_python( # noqa: WPS231
7773 """
7874 markdown .mimic (md )
7975 extra = options .get ("extra" , {})
80- output = run_python (code , html , ** extra )
76+ output = run_python (code , ** extra )
77+ stash = {}
78+ if html :
79+ placeholder = str (uuid4 ())
80+ stash [placeholder ] = output
81+ output = placeholder
8182 if source :
8283 output = add_source (source = code , location = source , output = output , language = "python" , tabs = tabs , ** extra )
83- return markdown .convert (output )
84+ return markdown .convert (output , stash = stash )
0 commit comments