pub struct Context { /* private fields */ }Expand description
An execution context for Python code.
This can be used to keep all global variables and imports intact between macro invocations:
let c = Context::new();
c.run(python! {
foo = 5
});
c.run(python! {
assert foo == 5
});You may also use it to inspect global variables after the execution of the Python code, or set global variables before running:
let c = Context::new();
c.set("x", 13);
c.run(python! {
foo = x + 2
});
assert_eq!(c.get::<i32>("foo"), 15);Implementations§
Source§impl Context
impl Context
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new context for running Python code.
This function panics if it fails to create the context.
Sourcepub fn get<T: for<'p> FromPyObject<'p>>(&self, name: &str) -> T
pub fn get<T: for<'p> FromPyObject<'p>>(&self, name: &str) -> T
Retrieve a global variable from the context.
This function panics if the variable doesn’t exist, or the conversion fails.
Sourcepub fn set<T: for<'p> IntoPyObject<'p>>(&self, name: &str, value: T)
pub fn set<T: for<'p> IntoPyObject<'p>>(&self, name: &str, value: T)
Set a global variable in the context.
This function panics if the conversion fails.
Sourcepub fn add_wrapped(
&self,
wrapper: &impl Fn(Python<'_>) -> PyResult<Bound<'_, PyCFunction>>,
)
pub fn add_wrapped( &self, wrapper: &impl Fn(Python<'_>) -> PyResult<Bound<'_, PyCFunction>>, )
Add a wrapped #[pyfunction] or #[pymodule] using its own __name__.
Use this with pyo3::wrap_pyfunction or pyo3::wrap_pymodule.
ⓘ
use pyo3::{prelude::*, wrap_pyfunction};
#[pyfunction]
fn get_five() -> i32 {
5
}
fn main() {
let c = Context::new();
c.add_wrapped(wrap_pyfunction!(get_five));
c.run(python! {
assert get_five() == 5
});
}Auto Trait Implementations§
impl Freeze for Context
impl !RefUnwindSafe for Context
impl Send for Context
impl Sync for Context
impl Unpin for Context
impl UnsafeUnpin for Context
impl UnwindSafe for Context
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
Mutably borrows from an owned value. Read more