pyodide.code
pyodide.code#
Classes:
|
This class allows fine control over the execution of a code block. |
Functions:
|
Runs a string as Python source code. |
|
Runs a code string asynchronously. |
|
Finds the imports in a Python source code string |
|
A wrapper for the JavaScript 'eval' function. |
|
Should we suppress output? |
- class pyodide.code.CodeRunner(source: str, *, return_mode: Literal['last_expr', 'last_expr_or_assign', 'none'] = 'last_expr', mode: str = 'exec', quiet_trailing_semicolon: bool = True, filename: str = '<exec>', flags: int = 0)#
This class allows fine control over the execution of a code block.
It is primarily intended for REPLs and other sophisticated consumers that may wish to add their own AST transformations, separately signal to the user when parsing is complete, etc. The simpler
eval_code
andeval_code_async
apis should be preferred when their flexibility suffices.- Parameters
source (
str
) – The Python source code to run.return_mode (
str
) –Specifies what should be returned, must be one of
'last_expr'
,'last_expr_or_assign'
or'none'
. On other values an exception is raised.'last_expr'
by default.'last_expr'
– return the last expression'last_expr_or_assign'
– return the last expression or the last assignment.'none'
– always returnNone
.
quiet_trailing_semicolon (
bool
) – Specifies whether a trailing semicolon should suppress the result or not. When this isTrue
executing"1+1 ;"
returnsNone
, when it isFalse
, executing"1+1 ;"
return2
.True
by default.filename (
str
) – The file name to use in error messages and stack traces.'<exec>'
by default.mode (
str
) – The “mode” to compile in. One of"exec"
,"single"
, or"eval"
. Defaults to"exec"
. For most purposes it’s unnecessary to use this argument. See the documentation for the built-in compile <https://docs.python.org/3/library/functions.html#compile> function.flags (
int
) – The flags to compile with. See the documentation for the built-in compile <https://docs.python.org/3/library/functions.html#compile> function.Attributes –
- astThe ast from parsing
source
. If you wish to do an ast transform, modify this variable before calling
CodeRunner.compile
.- codeOnce you call
CodeRunner.compile
the compiled code will be available in the code field. You can modify this variable before calling
CodeRunner.run
to do a code transform.
- astThe ast from parsing
- compile() _pyodide._base.CodeRunner #
Compile the current value of
self.ast
and store the result inself.code
.Can only be used once. Returns
self
(chainable).
- run(globals: Optional[dict[str, Any]] = None, locals: Optional[dict[str, Any]] = None) Optional[Any] #
Executes
self.code
.Can only be used after calling compile. The code may not use top level await, use
CodeRunner.run_async
for code that uses top level await.- Parameters
globals (
dict
) – The global scope in which to execute code. This is used as theglobals
parameter forexec
. Ifglobals
is absent, a new empty dictionary is used. See the exec documentation for more info.locals (
dict
) –The local scope in which to execute code. This is used as the
locals
parameter forexec
. Iflocals
is absent, the value ofglobals
is used. See the exec documentation for more info.
- Returns
If the last nonwhitespace character of
source
is a semicolon, returnNone
. If the last statement is an expression, return the result of the expression. Use thereturn_mode
andquiet_trailing_semicolon
parameters to modify this default behavior.- Return type
Any
- async run_async(globals: Optional[dict[str, Any]] = None, locals: Optional[dict[str, Any]] = None) None #
Runs
self.code
which may use top level await.Can only be used after calling
CodeRunner.compile
. Ifself.code
uses top level await, automatically awaits the resulting coroutine.- Parameters
globals (
dict
) –The global scope in which to execute code. This is used as the
globals
parameter forexec
. Ifglobals
is absent, a new empty dictionary is used. See the exec documentation for more info.locals (
dict
) –The local scope in which to execute code. This is used as the
locals
parameter forexec
. Iflocals
is absent, the value ofglobals
is used. See the exec documentation for more info.
- Returns
If the last nonwhitespace character of
source
is a semicolon, returnNone
. If the last statement is an expression, return the result of the expression. Use thereturn_mode
andquiet_trailing_semicolon
parameters to modify this default behavior.- Return type
Any
- pyodide.code.eval_code(source: str, globals: Optional[dict[str, Any]] = None, locals: Optional[dict[str, Any]] = None, *, return_mode: Literal['last_expr', 'last_expr_or_assign', 'none'] = 'last_expr', quiet_trailing_semicolon: bool = True, filename: str = '<exec>', flags: int = 0) Any #
Runs a string as Python source code.
- Parameters
source (
str
) – The Python source code to run.globals (
dict
) –The global scope in which to execute code. This is used as the
globals
parameter forexec
. Ifglobals
is absent, a new empty dictionary is used. See the exec documentation for more info.locals (
dict
) –The local scope in which to execute code. This is used as the
locals
parameter forexec
. Iflocals
is absent, the value ofglobals
is used. See the exec documentation for more info.return_mode (
str
) –Specifies what should be returned, must be one of
'last_expr'
,'last_expr_or_assign'
or'none'
. On other values an exception is raised.'last_expr'
by default.'last_expr'
– return the last expression'last_expr_or_assign'
– return the last expression or the last assignment.'none'
– always returnNone
.
quiet_trailing_semicolon (
bool
) – Specifies whether a trailing semicolon should suppress the result or not. When this isTrue
executing"1+1 ;"
returnsNone
, when it isFalse
, executing"1+1 ;"
return2
.True
by default.filename (
str
) – The file name to use in error messages and stack traces.'<exec>'
by default.
- Returns
If the last nonwhitespace character of
source
is a semicolon, returnNone
. If the last statement is an expression, return the result of the expression. Use thereturn_mode
andquiet_trailing_semicolon
parameters to modify this default behavior.- Return type
Any
Examples
>>> from pyodide.code import eval_code >>> source = "1 + 1" >>> eval_code(source) 2 >>> source = "1 + 1;" >>> eval_code(source, quiet_trailing_semicolon=True) >>> eval_code(source, quiet_trailing_semicolon=False) 2 >>> my_globals = { "y": "100" } >>> my_locals = { "y": "200" } >>> source = "print(locals()['y'], globals()['y'])" >>> eval_code(source, globals=my_globals, locals=my_locals) 200 100 >>> source = "test = 1 + 1" >>> eval_code(source, return_mode="last_expr_or_assign") 2 >>> eval_code(source, return_mode="last_expr") >>> eval_code(source, return_mode="none") >>> source = "print(pyodide)" # Pretend this is open('example_of_filename.py', 'r').read() >>> eval_code(source, filename="example_of_filename.py") # Trackback will show where in the file the error happened # ...File "example_of_filename.py", line 1, in <module>...NameError: name 'pyodide' is not defined
- async pyodide.code.eval_code_async(source: str, globals: Optional[dict[str, Any]] = None, locals: Optional[dict[str, Any]] = None, *, return_mode: Literal['last_expr', 'last_expr_or_assign', 'none'] = 'last_expr', quiet_trailing_semicolon: bool = True, filename: str = '<exec>', flags: int = 0) Any #
Runs a code string asynchronously.
Uses PyCF_ALLOW_TOP_LEVEL_AWAIT to compile the code.
- Parameters
source (
str
) – The Python source code to run.globals (
dict
) –The global scope in which to execute code. This is used as the
globals
parameter forexec
. Ifglobals
is absent, a new empty dictionary is used. See the exec documentation for more info.locals (
dict
) –The local scope in which to execute code. This is used as the
locals
parameter forexec
. Iflocals
is absent, the value ofglobals
is used. See the exec documentation for more info.return_mode (
str
) –Specifies what should be returned, must be one of
'last_expr'
,'last_expr_or_assign'
or'none'
. On other values an exception is raised.'last_expr'
by default.'last_expr'
– return the last expression'last_expr_or_assign'
– return the last expression or the last assignment.'none'
– always returnNone
.
quiet_trailing_semicolon (
bool
) – Specifies whether a trailing semicolon should suppress the result or not. When this isTrue
executing"1+1 ;"
returnsNone
, when it isFalse
, executing"1+1 ;"
return2
.True
by default.filename (
str
) – The file name to use in error messages and stack traces.'<exec>'
by default.
- Returns
If the last nonwhitespace character of
source
is a semicolon, returnNone
. If the last statement is an expression, return the result of the expression. Use thereturn_mode
andquiet_trailing_semicolon
parameters to modify this default behavior.- Return type
Any
- pyodide.code.find_imports(source: str) list[str] #
Finds the imports in a Python source code string
- Parameters
source (str) – The Python source code to inspect for imports.
- Returns
A list of module names that are imported in
source
. Ifsource
is not syntactically correct Python code (after dedenting), returns an empty list.- Return type
List[str]
Examples
>>> from pyodide import find_imports >>> source = "import numpy as np; import scipy.stats" >>> find_imports(source) ['numpy', 'scipy']
- pyodide.code.run_js(code: str, /) Any #
A wrapper for the JavaScript ‘eval’ function.
Runs ‘code’ as a Javascript code string and returns the result. Unlike JavaScript’s ‘eval’, if ‘code’ is not a string we raise a TypeError.
- pyodide.code.should_quiet(source: str) bool #
Should we suppress output?
Returns
True
if the last nonwhitespace character ofcode
is a semicolon.Examples
>>> should_quiet('1 + 1') False >>> should_quiet('1 + 1 ;') True >>> should_quiet('1 + 1 # comment ;') False