pub struct VirtualMachine {Show 17 fields
pub builtins: PyRef<PyModule>,
pub sys_module: PyRef<PyModule>,
pub ctx: PyRc<Context>,
pub wasm_id: Option<String>,
pub import_func: PyObjectRef,
pub profile_func: RefCell<PyObjectRef>,
pub trace_func: RefCell<PyObjectRef>,
pub use_tracing: Cell<bool>,
pub recursion_limit: Cell<usize>,
pub repr_guards: RefCell<HashSet<usize>>,
pub state: PyRc<PyGlobalState>,
pub initialized: bool,
pub async_gen_firstiter: RefCell<Option<PyObjectRef>>,
pub async_gen_finalizer: RefCell<Option<PyObjectRef>>,
pub asyncio_running_loop: RefCell<Option<PyObjectRef>>,
pub asyncio_running_task: RefCell<Option<PyObjectRef>>,
pub context_stack: RefCell<Vec<PyObjectRef>>,
/* private fields */
}Expand description
Per-thread execution context for a single interpreter (≈ CPython PyThreadState).
A VirtualMachine holds thread-local eval state (exceptions, recursion, frames,
datastack) plus shared references to interpreter-owned data (state,
builtins, sys_module, ctx). Multiple VMs may share the same
PyGlobalState via VirtualMachine::new_thread; distinct interpreters
each have their own PyGlobalState (see Interpreter::create_subinterpreter).
To construct the main VM of an interpreter, use Interpreter.
Fields§
§builtins: PyRef<PyModule>§sys_module: PyRef<PyModule>§ctx: PyRc<Context>§wasm_id: Option<String>§import_func: PyObjectRef§profile_func: RefCell<PyObjectRef>§trace_func: RefCell<PyObjectRef>§use_tracing: Cell<bool>§recursion_limit: Cell<usize>§repr_guards: RefCell<HashSet<usize>>§state: PyRc<PyGlobalState>§initialized: bool§async_gen_firstiter: RefCell<Option<PyObjectRef>>Async generator firstiter hook (per-thread, set via sys.set_asyncgen_hooks)
async_gen_finalizer: RefCell<Option<PyObjectRef>>Async generator finalizer hook (per-thread, set via sys.set_asyncgen_hooks)
asyncio_running_loop: RefCell<Option<PyObjectRef>>Current running asyncio event loop for this thread
asyncio_running_task: RefCell<Option<PyObjectRef>>Current running asyncio task for this thread
context_stack: RefCell<Vec<PyObjectRef>>Active Context stack for this thread and interpreter (PEP 567 / contextvars)
Implementations§
Source§impl VirtualMachine
impl VirtualMachine
Sourcepub fn print_exception(&self, exc: &Py<PyBaseException>)
pub fn print_exception(&self, exc: &Py<PyBaseException>)
Print exception chain by calling sys.excepthook
pub fn write_exception<W: Write>( &self, output: &mut W, exc: &Py<PyBaseException>, ) -> Result<(), W::Error>
Sourcepub fn write_exception_inner<W: Write>(
&self,
output: &mut W,
exc: &Py<PyBaseException>,
) -> Result<(), W::Error>
pub fn write_exception_inner<W: Write>( &self, output: &mut W, exc: &Py<PyBaseException>, ) -> Result<(), W::Error>
Print exception with traceback
pub fn split_exception( &self, exc: PyBaseExceptionRef, ) -> (PyObjectRef, PyObjectRef, PyObjectRef)
Sourcepub fn normalize_exception(
&self,
exc_type: PyObjectRef,
exc_val: PyObjectRef,
exc_tb: PyObjectRef,
) -> PyResult<PyBaseExceptionRef>
pub fn normalize_exception( &self, exc_type: PyObjectRef, exc_val: PyObjectRef, exc_tb: PyObjectRef, ) -> PyResult<PyBaseExceptionRef>
Similar to PyErr_NormalizeException in CPython
pub fn invoke_exception( &self, cls: &Py<PyType>, args: Vec<PyObjectRef>, ) -> PyResult<PyBaseExceptionRef>
Source§impl VirtualMachine
impl VirtualMachine
pub fn compile_string_object_with_flags( &self, source: &[u8], filename: &str, start: i32, flags: i32, feature_version: i32, optimize: i32, ) -> PyResult<PyObjectRef>
pub fn compile( &self, source: &str, mode: Mode, source_path: impl Into<String>, ) -> Result<PyRef<PyCode>, VmCompileError>
pub fn compile_with_opts( &self, source: &str, mode: Mode, source_path: impl Into<String>, opts: CompileOpts, ) -> Result<PyRef<PyCode>, VmCompileError>
Source§impl VirtualMachine
impl VirtualMachine
Sourcepub fn run_simple_string(&self, source: &str) -> PyResult
pub fn run_simple_string(&self, source: &str) -> PyResult
PyRun_SimpleString
Execute a string of Python code in a new scope with builtins.
Sourcepub fn run_string(
&self,
scope: Scope,
source: &str,
source_path: &str,
) -> PyResult
pub fn run_string( &self, scope: Scope, source: &str, source_path: &str, ) -> PyResult
PyRun_String
Execute a string of Python code with explicit scope and source path.
Sourcepub fn register_code_in_linecache(
&self,
code: &Py<PyCode>,
source: &str,
) -> PyResult<()>
pub fn register_code_in_linecache( &self, code: &Py<PyCode>, source: &str, ) -> PyResult<()>
Register a code object’s source in linecache._interactive_cache so that traceback can display source lines and caret indicators.
pub fn run_code_string( &self, scope: Scope, source: &str, source_path: &str, ) -> PyResult
use run_string instead
pub fn run_block_expr(&self, scope: Scope, source: &str) -> PyResult
Source§impl VirtualMachine
Collection of object creation helpers
impl VirtualMachine
Collection of object creation helpers
Sourcepub fn new_pyobj(&self, value: impl ToPyObject) -> PyObjectRef
pub fn new_pyobj(&self, value: impl ToPyObject) -> PyObjectRef
Create a new python object
pub fn new_tuple(&self, value: impl IntoPyTuple) -> PyTupleRef
pub fn new_module( &self, name: &str, dict: PyDictRef, doc: Option<PyStrRef>, ) -> PyRef<PyModule>
pub fn new_scope_with_builtins(&self) -> Scope
pub fn new_scope_with_main(&self) -> PyResult<Scope>
Sourcepub fn ensure_main_module(&self) -> PyResult<PyRef<PyModule>>
pub fn ensure_main_module(&self) -> PyResult<PyRef<PyModule>>
Create __main__ if it is missing and return it.
Sourcepub fn set_main_builtin_importer(
&self,
module_dict: &Py<PyDict>,
) -> PyResult<()>
pub fn set_main_builtin_importer( &self, module_dict: &Py<PyDict>, ) -> PyResult<()>
Set __main__.__loader__ to BuiltinImporter when it is missing or None.
Sourcepub fn main_namespace(&self) -> PyResult<PyDictRef>
pub fn main_namespace(&self) -> PyResult<PyDictRef>
__dict__ of this interpreter’s __main__ module.
pub fn new_function<F, FKind>(
&self,
name: &'static str,
f: F,
) -> PyRef<PyNativeFunction>where
F: IntoPyNativeFn<FKind>,
pub fn new_method<F, FKind>(
&self,
name: &'static str,
class: &'static Py<PyType>,
f: F,
) -> PyRef<PyMethodDescriptor>where
F: IntoPyNativeFn<FKind>,
Sourcepub fn new_simple_exception(
&self,
exc_type: PyTypeRef,
args: Vec<PyObjectRef>,
) -> PyBaseExceptionRef
pub fn new_simple_exception( &self, exc_type: PyTypeRef, args: Vec<PyObjectRef>, ) -> PyBaseExceptionRef
Allocate a BaseException-layout instance without running __new__/__init__.
Only valid when exc_type uses the BaseException payload. Extra-payload
types (OSError, UnicodeError, ExceptionGroup, SystemExit, …) must use
new_exception or
invoke_exception.
Sourcepub fn new_exception(
&self,
exc_type: PyTypeRef,
args: Vec<PyObjectRef>,
) -> PyBaseExceptionRef
pub fn new_exception( &self, exc_type: PyTypeRef, args: Vec<PyObjectRef>, ) -> PyBaseExceptionRef
Instantiate an exception with arguments.
BaseException-sized types use
new_simple_exception. Extra-payload types
run the type constructor so their fields are initialized. User-defined
types that override __new__/__init__ should still use
invoke_exception or
exceptions::ExceptionCtor.
Sourcepub fn new_payload_exception<T>(
&self,
cls: PyTypeRef,
args: FuncArgs,
) -> PyResult<PyRef<T>>
pub fn new_payload_exception<T>( &self, cls: PyTypeRef, args: FuncArgs, ) -> PyResult<PyRef<T>>
Construct a built-in exception type that carries a payload, directly
(py_new + slot_init), without routing through PyType::call.
Only valid for a built-in T whose exact type is known at compile time.
pub fn new_os_error(&self, msg: impl ToPyObject) -> PyRef<PyBaseException>
pub fn new_os_subtype_error( &self, exc_type: PyTypeRef, errno: Option<i32>, msg: impl ToPyObject, ) -> PyRef<PyOSError>
Sourcepub fn new_exception_empty(&self, exc_type: PyTypeRef) -> PyBaseExceptionRef
pub fn new_exception_empty(&self, exc_type: PyTypeRef) -> PyBaseExceptionRef
Instantiate an exception with no arguments.
Sourcepub fn new_exception_msg(
&self,
exc_type: PyTypeRef,
msg: Wtf8Buf,
) -> PyBaseExceptionRef
pub fn new_exception_msg( &self, exc_type: PyTypeRef, msg: Wtf8Buf, ) -> PyBaseExceptionRef
Instantiate an exception with msg as the only argument.
Sourcepub fn new_exception_msg_dict(
&self,
exc_type: PyTypeRef,
msg: Wtf8Buf,
dict: PyDictRef,
) -> PyBaseExceptionRef
pub fn new_exception_msg_dict( &self, exc_type: PyTypeRef, msg: Wtf8Buf, dict: PyDictRef, ) -> PyBaseExceptionRef
Instantiate an exception with msg as the only argument and dict for object
This function should only be used with builtin exception types; if a user-defined exception
type is passed in, it may not be fully initialized; try using
vm.invoke_exception() or
exceptions::ExceptionCtor instead.
pub fn new_no_attribute_error( &self, obj: PyObjectRef, name: PyStrRef, ) -> PyBaseExceptionRef
pub fn new_name_error( &self, msg: impl Into<Wtf8Buf>, name: PyStrRef, ) -> PyBaseExceptionRef
Sourcepub fn new_arity_type_error(
&self,
func_name: &str,
arity: RangeInclusive<usize>,
num_given: usize,
) -> PyBaseExceptionRef
pub fn new_arity_type_error( &self, func_name: &str, arity: RangeInclusive<usize>, num_given: usize, ) -> PyBaseExceptionRef
The error a call that passed the wrong number of arguments gets. The
name is the function the call was for; Self::NAME is the one a slot
wants. _PyArg_CheckPositional
Sourcepub fn new_unexpected_keyword_type_error(
&self,
func_name: Option<&str>,
keyword: &str,
) -> PyBaseExceptionRef
pub fn new_unexpected_keyword_type_error( &self, func_name: Option<&str>, keyword: &str, ) -> PyBaseExceptionRef
The error a call that passed a keyword the function doesn’t take gets.
The name is left off where the parser has none of its own, the way
_PyArg_Parser.fname is NULL. _PyArg_UnpackKeywords
pub fn new_unsupported_unary_error( &self, a: &PyObject, op: &str, ) -> PyBaseExceptionRef
pub fn new_unsupported_bin_op_error( &self, a: &PyObject, b: &PyObject, op: &str, ) -> PyBaseExceptionRef
pub fn new_unsupported_ternary_op_error( &self, a: &PyObject, b: &PyObject, c: &PyObject, op: &str, ) -> PyBaseExceptionRef
Sourcepub fn new_last_os_error(&self) -> PyBaseExceptionRef
pub fn new_last_os_error(&self) -> PyBaseExceptionRef
Create a new OSError from the last OS error.
On windows, windows-sys errors are expected to be handled by this function.
This is identical to new_last_errno_error on non-Windows platforms.
Sourcepub fn new_last_errno_error(&self) -> PyBaseExceptionRef
pub fn new_last_errno_error(&self) -> PyBaseExceptionRef
Create a new OSError from the last POSIX errno.
On windows, CRT errno are expected to be handled by this function.
This is identical to new_last_os_error on non-Windows platforms.
pub fn new_errno_error( &self, errno: i32, msg: impl ToPyObject, ) -> PyRef<PyOSError>
pub fn new_unicode_decode_error( &self, encoding: PyStrRef, object: PyBytesRef, start: usize, end: usize, reason: PyStrRef, ) -> PyBaseExceptionRef
pub fn new_unicode_encode_error( &self, encoding: PyStrRef, object: PyStrRef, start: usize, end: usize, reason: PyStrRef, ) -> PyBaseExceptionRef
pub fn new_key_error(&self, obj: PyObjectRef) -> PyBaseExceptionRef
pub fn new_syntax_error_maybe_incomplete( &self, error: &CompileError, source: Option<&str>, allow_incomplete: bool, ) -> PyBaseExceptionRef
pub fn new_syntax_error( &self, error: &CompileError, source: Option<&str>, ) -> PyBaseExceptionRef
pub fn new_import_error( &self, msg: impl Into<Wtf8Buf>, name: impl Into<PyStrRef>, ) -> PyBaseExceptionRef
pub fn new_system_exit(&self, args: FuncArgs) -> PyBaseExceptionRef
pub fn new_stop_iteration( &self, value: Option<PyObjectRef>, ) -> PyBaseExceptionRef
Sourcepub fn no_memory_error(&self) -> PyBaseExceptionRef
pub fn no_memory_error(&self) -> PyBaseExceptionRef
Create a MemoryError with no arguments, for reporting a failed allocation.
Served from the MemoryError freelist when a husk is available, so the raise itself does not allocate; falls back to a fresh allocation when the freelist is empty (#8536).
Sourcepub fn new_lookup_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_lookup_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python LookupError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_eof_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_eof_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python EOFError object. Useful for raising errors from python functions implemented in rust.
pub fn new_attribute_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Sourcepub fn new_type_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_type_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python TypeError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_system_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_system_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python SystemError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_value_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_value_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python ValueError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_buffer_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_buffer_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python BufferError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_index_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_index_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python IndexError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_not_implemented_error(
&self,
msg: impl Into<Wtf8Buf>,
) -> PyBaseExceptionRef
pub fn new_not_implemented_error( &self, msg: impl Into<Wtf8Buf>, ) -> PyBaseExceptionRef
Create a new python NotImplementedError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_recursion_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_recursion_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python RecursionError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_zero_division_error(
&self,
msg: impl Into<Wtf8Buf>,
) -> PyBaseExceptionRef
pub fn new_zero_division_error( &self, msg: impl Into<Wtf8Buf>, ) -> PyBaseExceptionRef
Create a new python ZeroDivisionError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_overflow_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_overflow_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python OverflowError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_runtime_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_runtime_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python RuntimeError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_python_finalization_error(
&self,
msg: impl Into<Wtf8Buf>,
) -> PyBaseExceptionRef
pub fn new_python_finalization_error( &self, msg: impl Into<Wtf8Buf>, ) -> PyBaseExceptionRef
Create a new python PythonFinalizationError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_memory_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_memory_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python MemoryError object. Useful for raising errors from python functions implemented in rust.
Sourcepub fn new_assertion_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
pub fn new_assertion_error(&self, msg: impl Into<Wtf8Buf>) -> PyBaseExceptionRef
Create a new python AssertionError object. Useful for raising errors from python functions implemented in rust.
pub fn new_unbound_local_error( &self, msg: impl Into<Wtf8Buf>, ) -> PyBaseExceptionRef
Source§impl VirtualMachine
PyObject support
impl VirtualMachine
PyObject support
pub fn unwrap_pyresult<T>(&self, result: PyResult<T>) -> T
pub fn expect_pyresult<T>(&self, result: PyResult<T>, msg: &str) -> T
pub fn option_if_none(&self, obj: PyObjectRef) -> Option<PyObjectRef>
pub fn unwrap_or_none(&self, obj: Option<PyObjectRef>) -> PyObjectRef
pub fn call_get_descriptor_specific( &self, descr: &PyObject, obj: Option<&PyObject>, cls: Option<&PyObject>, ) -> Option<PyResult>
pub fn call_get_descriptor( &self, descr: &PyObject, obj: &PyObject, ) -> Option<PyResult>
pub fn call_if_get_descriptor( &self, attr: &PyObject, obj: PyObjectRef, ) -> PyResult
pub fn call_method<T>(
&self,
obj: &PyObject,
method_name: &str,
args: T,
) -> PyResultwhere
T: IntoFuncArgs,
pub fn dir(&self, obj: Option<PyObjectRef>) -> PyResult<PyList>
Sourcepub fn print(&self, args: impl IntoFuncArgs) -> PyResult<()>
pub fn print(&self, args: impl IntoFuncArgs) -> PyResult<()>
Same as builtins.print in Python. A convenience function to provide a simple way to print objects for debug purpose.
pub fn invoke(&self, obj: &impl AsObject, args: impl IntoFuncArgs) -> PyResult
in favor of obj.call(args, vm)
Source§impl VirtualMachine
Collection of operators
impl VirtualMachine
Collection of operators
pub fn bool_eq(&self, a: &PyObject, b: &PyObject) -> PyResult<bool>
pub fn identical_or_equal(&self, a: &PyObject, b: &PyObject) -> PyResult<bool>
pub fn bool_seq_lt(&self, a: &PyObject, b: &PyObject) -> PyResult<Option<bool>>
pub fn bool_seq_gt(&self, a: &PyObject, b: &PyObject) -> PyResult<Option<bool>>
pub fn length_hint_opt(&self, iter: PyObjectRef) -> PyResult<Option<usize>>
Sourcepub fn check_repeat_or_overflow_error(
&self,
length: usize,
n: isize,
) -> PyResult<usize>
pub fn check_repeat_or_overflow_error( &self, length: usize, n: isize, ) -> PyResult<usize>
Checks that the multiplication is able to be performed. On Ok returns the index as a usize for sequences to be able to use immediately.
Sourcepub fn new_zeroed_bytes(&self, len: usize) -> PyResult<Vec<u8>>
pub fn new_zeroed_bytes(&self, len: usize) -> PyResult<Vec<u8>>
vec![0; len] for a length that came from Python, where a request too
large to satisfy is a MemoryError rather than an aborted process.
The bytes are left for the allocator to zero, so a large request costs no more than the pages that are actually written to.
Sourcepub fn binary_op1(
&self,
a: &PyObject,
b: &PyObject,
op_slot: PyNumberBinaryOp,
) -> PyResult
pub fn binary_op1( &self, a: &PyObject, b: &PyObject, op_slot: PyNumberBinaryOp, ) -> PyResult
Calling scheme used for binary operations:
Order operations are tried until either a valid result or error:
b.rop(b,a)[*], a.op(a,b), b.rop(b,a)
[*] - only when Py_TYPE(a) != Py_TYPE(b) && Py_TYPE(b) is a subclass of Py_TYPE(a)
pub fn binary_op( &self, a: &PyObject, b: &PyObject, op_slot: PyNumberBinaryOp, op: &str, ) -> PyResult
pub fn _sub(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _mod(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _divmod(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _lshift(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _rshift(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _and(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _xor(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _or(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _floordiv(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _truediv(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _matmul(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _isub(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _imod(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _ilshift(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _irshift(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _iand(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _ixor(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _ior(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _ifloordiv(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _itruediv(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _imatmul(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _pow(&self, a: &PyObject, b: &PyObject, c: &PyObject) -> PyResult
pub fn _ipow(&self, a: &PyObject, b: &PyObject, c: &PyObject) -> PyResult
pub fn _add(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _iadd(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _mul(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _imul(&self, a: &PyObject, b: &PyObject) -> PyResult
pub fn _abs(&self, a: &PyObject) -> PyResult<PyObjectRef>
pub fn _pos(&self, a: &PyObject) -> PyResult
pub fn _neg(&self, a: &PyObject) -> PyResult
pub fn _invert(&self, a: &PyObject) -> PyResult
pub fn format( &self, obj: &PyObject, format_spec: PyStrRef, ) -> PyResult<PyStrRef>
pub fn format_utf8( &self, obj: &PyObject, format_spec: PyStrRef, ) -> PyResult<PyRef<PyUtf8Str>>
pub fn _contains( &self, haystack: &PyObject, needle: &PyObject, ) -> PyResult<bool>
Source§impl VirtualMachine
impl VirtualMachine
Sourcepub fn allow_threads<R>(&self, f: impl FnOnce() -> R) -> R
pub fn allow_threads<R>(&self, f: impl FnOnce() -> R) -> R
Temporarily detach the current thread (ATTACHED → DETACHED) while
running f, then re-attach afterwards. Allows stop_the_world to
park this thread during blocking syscalls.
Equivalent to CPython’s Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS.
Sourcepub fn attach_for_callback<R>(&self, f: impl FnOnce() -> R) -> R
pub fn attach_for_callback<R>(&self, f: impl FnOnce() -> R) -> R
Re-attach the current thread for the duration of f, then return it to
where it was. The inverse of allow_threads, for
a callback that runs Python from inside a call this thread detached for.
Equivalent to PyGILState_Ensure / PyGILState_Release around such a
callback.
Sourcepub fn set_user_signal_channel(&mut self, signal_rx: UserSignalReceiver)
pub fn set_user_signal_channel(&mut self, signal_rx: UserSignalReceiver)
Set the custom signal channel for the interpreter
Sourcepub fn run_pyc_bytes(&self, pyc_bytes: &[u8], scope: Scope) -> PyResult<()>
pub fn run_pyc_bytes(&self, pyc_bytes: &[u8], scope: Scope) -> PyResult<()>
Execute Python bytecode (.pyc) from an in-memory buffer.
When the RustPython CLI is available, .pyc files are normally executed by
invoking rustpython <input>.pyc. This method provides an alternative for
environments where the binary is unavailable or file I/O is restricted
(e.g. WASM).
§Preparing a .pyc file
First, compile a Python source file into bytecode:
# Generate a .pyc file
$ rustpython -m py_compile <input>.py§Running the bytecode
Load the resulting .pyc file into memory and execute it using the VM:
use rustpython_vm::Interpreter;
Interpreter::without_stdlib(Default::default()).enter(|vm| {
let bytes = std::fs::read("__pycache__/<input>.rustpython-314.pyc").unwrap();
let main_scope = vm.new_scope_with_main().unwrap();
vm.run_pyc_bytes(&bytes, main_scope);
});pub fn run_code_obj(&self, code: PyRef<PyCode>, scope: Scope) -> PyResult
pub fn run_unraisable( &self, e: PyBaseExceptionRef, msg: Option<String>, object: PyObjectRef, )
Sourcepub fn run_frame_fast(&self, iframe: &mut InterpreterFrame) -> PyResult
pub fn run_frame_fast(&self, iframe: &mut InterpreterFrame) -> PyResult
Run a stack-allocated InterpreterFrame without heap allocation.
Uses a trampoline loop to flatten Python-to-Python calls: when the
bytecode loop returns TailCall, the trampoline swaps to the new
frame without adding a Rust stack frame.
pub fn run_frame(&self, frame: FrameObjectRef) -> PyResult
Sourcepub fn finalize_modules(&self)
pub fn finalize_modules(&self)
Clear module references during shutdown. Follows the same phased algorithm as pylifecycle.c finalize_modules(): no hardcoded module names, reverse import order, only builtins/sys last.
pub fn current_recursion_depth(&self) -> usize
Sourcepub fn with_recursion<R, F: FnOnce() -> PyResult<R>>(
&self,
_where: &str,
f: F,
) -> PyResult<R>
pub fn with_recursion<R, F: FnOnce() -> PyResult<R>>( &self, _where: &str, f: F, ) -> PyResult<R>
Used to run the body of a (possibly) recursive function. It will raise a
RecursionError if recursive functions are nested far too many times,
preventing a stack overflow.
Py_EnterRecursiveCall: bounds native recursion that pushes no Python
frame, against the native stack. That is a separate budget from the
frame limit sys.setrecursionlimit() sets, so nesting counted here does
not come out of what Python code has left to call with.
pub fn with_frame<R, F: FnOnce(FrameObjectRef) -> PyResult<R>>( &self, frame: FrameObjectRef, f: F, ) -> PyResult<R>
Sourcepub fn resume_gen_frame<R, F: FnOnce(&Py<FrameObject>) -> PyResult<R>>(
&self,
frame: &FrameObjectRef,
exc: Option<PyBaseExceptionRef>,
f: F,
) -> PyResult<R>
pub fn resume_gen_frame<R, F: FnOnce(&Py<FrameObject>) -> PyResult<R>>( &self, frame: &FrameObjectRef, exc: Option<PyBaseExceptionRef>, f: F, ) -> PyResult<R>
FrameObject execution for generator/coroutine resume. Pushes a new exc_info slot (gi_exc_state) onto the chain, linking the generator’s saved handled-exception.
Sourcepub fn compile_opts(&self) -> CompileOpts
pub fn compile_opts(&self) -> CompileOpts
Returns a basic CompileOpts instance with options accurate to the vm. Used
as the CompileOpts for vm.compile().
Sourcepub fn audit<A: IntoFuncArgs>(
&self,
event: &str,
args: impl FnOnce() -> A,
) -> PyResult<()>
pub fn audit<A: IntoFuncArgs>( &self, event: &str, args: impl FnOnce() -> A, ) -> PyResult<()>
PySys_Audit: raise audit event to the registered hooks. args is only built when a hook
is registered.
pub fn current_frame(&self) -> Option<FrameObjectRef>
pub fn current_locals(&self) -> PyResult<ArgMapping>
pub fn current_globals(&self) -> PyDictRef
pub fn try_class( &self, module: &'static str, class: &'static str, ) -> PyResult<PyTypeRef>
pub fn class(&self, module: &'static str, class: &'static str) -> PyTypeRef
Sourcepub fn import<'a>(
&self,
module_name: impl AsPyStr<'a>,
level: usize,
) -> PyResult
pub fn import<'a>( &self, module_name: impl AsPyStr<'a>, level: usize, ) -> PyResult
Call Python import function without from_list.
Roughly equivalent to import module_name or import top.submodule.
See also VirtualMachine::import_from for more advanced import.
See also rustpython_vm::import::import_source and other primitive import functions.
Sourcepub fn import_from<'a>(
&self,
module_name: impl AsPyStr<'a>,
from_list: impl Into<PyObjectRef>,
level: usize,
) -> PyResult
pub fn import_from<'a>( &self, module_name: impl AsPyStr<'a>, from_list: impl Into<PyObjectRef>, level: usize, ) -> PyResult
Call Python import function caller with from_list.
Roughly equivalent to from module_name import item1, item2 or from top.submodule import item1, item2
Sourcepub fn eval_get_builtin(&self, name: &'static PyStrInterned) -> PyResult
pub fn eval_get_builtin(&self, name: &'static PyStrInterned) -> PyResult
Look up name in the current frame’s builtins (_PyEval_GetBuiltin).
A missing key becomes AttributeError with that name.
pub fn extract_elements_with<T, F>( &self, value: &PyObject, func: F, ) -> PyResult<Vec<T>>
Sourcepub fn extract_elements_sized<T, F>(
&self,
value: &PyObject,
held: &dyn Fn() -> usize,
func: F,
) -> PyResult<Vec<T>>
pub fn extract_elements_sized<T, F>( &self, value: &PyObject, held: &dyn Fn() -> usize, func: F, ) -> PyResult<Vec<T>>
Self::extract_elements_with for a caller that asks the iterable
itself how much room to take, the way list_extend() does. held
answers how many elements the caller already has, and is read after the
iterable has been asked, since asking runs its code.
Sourcepub fn map_iterable_object_sized<F, R>(
&self,
obj: &PyObject,
f: F,
) -> PyResult<PyResult<Vec<R>>>
pub fn map_iterable_object_sized<F, R>( &self, obj: &PyObject, f: F, ) -> PyResult<PyResult<Vec<R>>>
Self::map_iterable_object for a caller that asks the object it was
handed how long it is.
pub fn map_iterable_object<F, R>( &self, obj: &PyObject, f: F, ) -> PyResult<PyResult<Vec<R>>>
pub fn get_attribute_opt<'a>( &self, obj: &PyObject, attr_name: impl AsPyStr<'a>, ) -> PyResult<Option<PyObjectRef>>
pub fn set_attribute_error_context( &self, exc: &Py<PyBaseException>, obj: PyObjectRef, name: PyStrRef, )
pub fn get_method_or_type_error<F>( &self, obj: PyObjectRef, method_name: &'static PyStrInterned, err_msg: F, ) -> PyResult
Sourcepub fn check_signals(&self) -> PyResult<()>
pub fn check_signals(&self) -> PyResult<()>
Checks for triggered signals and calls the appropriate handlers. A no-op on platforms where signals are not supported.
pub fn current_exception(&self) -> Option<PyBaseExceptionRef>
Sourcepub fn set_exception(&self, exc: Option<PyBaseExceptionRef>)
pub fn set_exception(&self, exc: Option<PyBaseExceptionRef>)
Set the current exc_info slot value (PUSH_EXC_INFO / POP_EXCEPT).
pub fn take_raised_exception(&self) -> Option<PyBaseExceptionRef>
pub fn handle_exit_exception(&self, exc: PyBaseExceptionRef) -> u32
pub fn insert_sys_path(&self, obj: PyObjectRef) -> PyResult<()>
pub fn run_module(&self, module: &str) -> PyResult<()>
pub fn fs_encoding(&self) -> &'static PyStrInterned
pub fn fs_encode_errors(&self) -> &'static PyUtf8StrInterned
pub fn fsdecode(&self, s: impl Into<OsString>) -> PyStrRef
pub fn fsencode<'a>(&self, s: &'a Py<PyStr>) -> PyResult<Cow<'a, OsStr>>
Trait Implementations§
Auto Trait Implementations§
impl !Freeze for VirtualMachine
impl !RefUnwindSafe for VirtualMachine
impl !Send for VirtualMachine
impl !Sync for VirtualMachine
impl !UnwindSafe for VirtualMachine
impl Unpin for VirtualMachine
impl UnsafeUnpin for VirtualMachine
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<T> ErasedDestructor for Twhere
T: 'static,
impl<T> Helper for T
Source§impl<T, U> ImaginaryInto<U> for Twhere
U: ImaginaryFrom<T>,
impl<T, U> ImaginaryInto<U> for Twhere
U: ImaginaryFrom<T>,
fn imaginary_into(self) -> U
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more