pyodide.code#

Classes:

CodeRunner(source, *[, return_mode, mode, ...])

This class allows fine control over the execution of a code block.

Functions:

eval_code(source[, globals, locals, ...])

Runs a string as Python source code.

eval_code_async(source[, globals, locals, ...])

Runs a code string asynchronously.

find_imports(source)

Finds the imports in a Python source code string

run_js(code, /)

A wrapper for the eval() function.

should_quiet(source, /)

Should we suppress output?

class pyodide.code.CodeRunner(source, *, return_mode='last_expr', mode='exec', quiet_trailing_semicolon=True, filename='<exec>', flags=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() and eval_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 is True executing "1+1;" returns None, when it is False, executing "1+1;" return 2. 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() function.

  • flags (int) – The flags to compile with. See the documentation for the built-in compile() 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 calling CodeRunner.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 calling CodeRunner.run() to do a code transform.

compile()#

Compile the current value of self.ast and store the result in self.code.

Can only be used once. Returns self (chainable).

Return type:

CodeRunner

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 the globals parameter for exec(). If globals 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 the locals parameter for exec(). If locals is absent, the value of globals is used.

Return type:

Any

Returns:

If the last nonwhitespace character of source is a semicolon, return None. If the last statement is an expression, return the result of the expression. Use the return_mode and quiet_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(). If self.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 the globals parameter for exec(). If globals 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 the locals parameter for exec(). If locals is absent, the value of globals is used.

Return type:

Any

Returns:

If the last nonwhitespace character of source is a semicolon, return None. If the last statement is an expression, return the result of the expression. Use the return_mode and quiet_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)#

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 the globals parameter for exec(). If globals 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 the locals parameter for exec(). If locals is absent, the value of globals 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 is True executing "1+1 ;" returns None, when it is False, executing "1+1 ;" return 2. 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-in compile() function.

Return type:

Any

Returns:

If the last nonwhitespace character of source is a semicolon, return None. If the last statement is an expression, return the result of the expression. Use the return_mode and quiet_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)#

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 the globals parameter for exec(). If globals 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 the locals parameter for exec(). If locals is absent, the value of globals 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 is True executing "1+1 ;" returns None, when it is False, executing "1+1 ;" return 2. 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-in compile() function.

Return type:

Any

Returns:

If the last nonwhitespace character of source is a semicolon, return None. If the last statement is an expression, return the result of the expression. Use the return_mode and quiet_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:

list[str]

Returns:

A list of module names that are imported in source. If source 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.run_js(code, /)#

A wrapper for the eval() function.

Runs code as a Javascript code string and returns the result. Unlike eval(), if code is not a string we raise a TypeError.

Parameters:

code (str) –

Return type:

Any

pyodide.code.should_quiet(source, /)#

Should we suppress output?

Return type:

bool

Returns:

True if the last nonwhitespace character of source is a semicolon.

Examples

>>> should_quiet('1 + 1')
False
>>> should_quiet('1 + 1 ;')
True
>>> should_quiet('1 + 1 # comment ;')
False
Parameters:

source (str) –