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 |
|
Call the function ignoring extra arguments |
|
Decorator which creates a function that ignores extra arguments |
|
A wrapper for the |
|
Should we suppress output? |
- class pyodide.code.CodeRunner(source, *, return_mode='last_expr', mode='exec', quiet_trailing_semicolon=True, filename='<exec>', flags=0, dont_inherit=False, optimize=-1)#
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 (
Literal
['last_expr'
,'last_expr_or_assign'
,'none'
]) –Specifies what should be returned. The options are:
- ’last_expr’:
return the last expression
- ’last_expr_or_assign’:
return the last expression or the last assignment.
- ’none’:
always return
None
.
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-incompile()
function.flags (
int
) – The flags to compile with. See the documentation for the built-incompile()
function.dont_inherit (
bool
) – Whether to inherit__future__
imports from the outer code. See the documentation for the built-incompile()
function.optimize (
int
) – Specifies the optimization level of the compiler. See the documentation for the built-incompile()
function.
Examples
>>> source = "1 + 1" >>> code_runner = CodeRunner(source) >>> code_runner.compile() <_pyodide._base.CodeRunner object at 0x...> >>> code_runner.run() 2 >>> my_globals = {"x": 20} >>> my_locals = {"y": 5} >>> source = "x + y" >>> code_runner = CodeRunner(source) >>> code_runner.compile() <_pyodide._base.CodeRunner object at 0x...> >>> code_runner.run(globals=my_globals, locals=my_locals) 25
- ast: Module#
The ast from parsing
source
. If you wish to do an ast transform, modify this variable before callingCodeRunner.compile()
.
-
code:
Optional
[CodeType
]# Once you call
CodeRunner.compile()
the compiled code will be available in the code field. You can modify this variable before callingCodeRunner.run()
to do a code transform.
- compile()#
Compile the current value of
self.ast
and store the result inself.code
.Can only be used once. Returns
self
(chainable).- Return type:
- run(globals=None, locals=None)#
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 (
Optional
[dict
[str
,Any
]]) – The global scope in which to execute code. This is used as theglobals
parameter forexec()
. Ifglobals
is absent, a new empty dictionary is used.locals (
Optional
[dict
[str
,Any
]]) – The local scope in which to execute code. This is used as thelocals
parameter forexec()
. Iflocals
is absent, the value ofglobals
is used.
- Return type:
- 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.
- async run_async(globals=None, locals=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 (
Optional
[dict
[str
,Any
]]) – The global scope in which to execute code. This is used as theglobals
parameter forexec()
. Ifglobals
is absent, a new empty dictionary is used.locals (
Optional
[dict
[str
,Any
]]) – The local scope in which to execute code. This is used as thelocals
parameter forexec()
. Iflocals
is absent, the value ofglobals
is used.
- Return type:
- 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.
- pyodide.code.eval_code(source, globals=None, locals=None, *, return_mode='last_expr', quiet_trailing_semicolon=True, filename='<exec>', flags=0, dont_inherit=False, optimize=-1)#
Runs a string as Python source code.
- Parameters:
source (
str
) – The Python source code to run.globals (
Optional
[dict
[str
,Any
]]) – The global scope in which to execute code. This is used as theglobals
parameter forexec()
. Ifglobals
is absent, a new empty dictionary is used.locals (
Optional
[dict
[str
,Any
]]) – The local scope in which to execute code. This is used as thelocals
parameter forexec()
. Iflocals
is absent, the value ofglobals
is used.return_mode (
Literal
['last_expr'
,'last_expr_or_assign'
,'none'
]) –Specifies what should be returned. The options are:
- ’last_expr’:
return the last expression
- ’last_expr_or_assign’:
return the last expression or the last assignment.
- ’none’:
always return
None
.
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.flags (
int
) – The flags to compile with. See the documentation for the built-incompile()
function.
- Return type:
- 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.
Examples
>>> 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") Traceback (most recent call last): ... File "example_of_filename.py", line 1, in <module> print(pyodide) ^^^^^^^ NameError: name 'pyodide' is not defined
- async pyodide.code.eval_code_async(source, globals=None, locals=None, *, return_mode='last_expr', quiet_trailing_semicolon=True, filename='<exec>', flags=0, dont_inherit=False, optimize=-1)#
Runs a code string asynchronously.
Uses
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
to compile the code.- Parameters:
source (
str
) – The Python source code to run.globals (
Optional
[dict
[str
,Any
]]) – The global scope in which to execute code. This is used as theglobals
parameter forexec()
. Ifglobals
is absent, a new empty dictionary is used.locals (
Optional
[dict
[str
,Any
]]) – The local scope in which to execute code. This is used as thelocals
parameter forexec()
. Iflocals
is absent, the value ofglobals
is used.return_mode (
Literal
['last_expr'
,'last_expr_or_assign'
,'none'
]) –Specifies what should be returned. The options are:
- ’last_expr’:
return the last expression
- ’last_expr_or_assign’:
return the last expression or the last assignment.
- ’none’:
always return
None
.
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.flags (
int
) – The flags to compile with. See the documentation for the built-incompile()
function.dont_inherit (
bool
) –optimize (
int
) –
- Return type:
- 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.
- pyodide.code.find_imports(source)#
Finds the imports in a Python source code string
- Parameters:
source (
str
) – The Python source code to inspect for imports.- Return type:
- Returns:
A list of module names that are imported in
source
. Ifsource
is not syntactically correct Python code (after dedenting), returns an empty list.
Examples
>>> source = "import numpy as np; import scipy.stats" >>> find_imports(source) ['numpy', 'scipy']
- pyodide.code.relaxed_call(func, *args, **kwargs)#
Call the function ignoring extra arguments
If extra positional or keyword arguments are provided they will be discarded.
- pyodide.code.relaxed_wrap(func)#
Decorator which creates a function that ignores extra arguments
If extra positional or keyword arguments are provided they will be discarded.
- pyodide.code.run_js(code, /)#
A wrapper for the
eval()
function.Runs
code
as a Javascript code string and returns the result. Unlikeeval()
, ifcode
is not a string we raise aTypeError
.