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 JavaScript 'eval' function.

should_quiet(source)

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 and eval_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 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 <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.

compile() _pyodide._base.CodeRunner#

Compile the current value of self.ast and store the result in self.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 the globals parameter for exec. If globals 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 for exec. If locals is absent, the value of globals is used. See the exec documentation for more info.

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.

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. If self.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 for exec. If globals 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 for exec. If locals is absent, the value of globals is used. See the exec documentation for more info.

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.

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

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.

Return type

Any

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

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.

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. If source 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 of code is a semicolon.

Examples

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