pub struct PythonObject(pub Py<PyAny>);python only.Expand description
Wrapper around PyObject from pyo3 with additional trait impls.
Tuple Fields§
§0: Py<PyAny>Implementations§
Source§impl PythonObject
impl PythonObject
pub fn serialize_with_pyversion<T, S>( value: &T, serializer: S, ) -> Result<S::Ok, S::Error>
serde only.pub fn deserialize_with_pyversion<'de, T, D>(d: D) -> Result<T, D::Error>
serde only.Methods from Deref<Target = Py<PyAny>>§
pub fn as_ptr(&self) -> *mut PyObject
pub fn as_ptr(&self) -> *mut PyObject
Returns the raw FFI pointer represented by self.
§Safety
Callers are responsible for ensuring that the pointer does not outlive self.
The reference is borrowed; callers should not decrease the reference count when they are finished with the pointer.
pub fn as_any(&self) -> &Py<PyAny>
pub fn as_any(&self) -> &Py<PyAny>
Helper to cast to Py<PyAny>.
pub fn borrow<'py>(&'py self, py: Python<'py>) -> PyRef<'py, T>
pub fn borrow<'py>(&'py self, py: Python<'py>) -> PyRef<'py, T>
Immutably borrows the value T.
This borrow lasts while the returned [PyRef] exists.
Multiple immutable borrows can be taken out at the same time.
For frozen classes, the simpler [get][Self::get] is available.
Equivalent to self.bind(py).borrow() - see [Bound::borrow].
§Examples
#[pyclass]
struct Foo {
inner: u8,
}
Python::attach(|py| -> PyResult<()> {
let foo: Py<Foo> = Py::new(py, Foo { inner: 73 })?;
let inner: &u8 = &foo.borrow(py).inner;
assert_eq!(*inner, 73);
Ok(())
})?;§Panics
Panics if the value is currently mutably borrowed. For a non-panicking variant, use
try_borrow.
pub fn borrow_mut<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T>where
T: PyClass<Frozen = False>,
pub fn borrow_mut<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T>where
T: PyClass<Frozen = False>,
Mutably borrows the value T.
This borrow lasts while the returned [PyRefMut] exists.
Equivalent to self.bind(py).borrow_mut() - see [Bound::borrow_mut].
§Examples
#[pyclass]
struct Foo {
inner: u8,
}
Python::attach(|py| -> PyResult<()> {
let foo: Py<Foo> = Py::new(py, Foo { inner: 73 })?;
foo.borrow_mut(py).inner = 35;
assert_eq!(foo.borrow(py).inner, 35);
Ok(())
})?;§Panics
Panics if the value is currently borrowed. For a non-panicking variant, use
try_borrow_mut.
pub fn try_borrow<'py>(
&'py self,
py: Python<'py>,
) -> Result<PyRef<'py, T>, PyBorrowError>
pub fn try_borrow<'py>( &'py self, py: Python<'py>, ) -> Result<PyRef<'py, T>, PyBorrowError>
Attempts to immutably borrow the value T, returning an error if the value is currently mutably borrowed.
The borrow lasts while the returned [PyRef] exists.
This is the non-panicking variant of borrow.
For frozen classes, the simpler [get][Self::get] is available.
Equivalent to self.bind(py).try_borrow() - see [Bound::try_borrow].
pub fn try_borrow_mut<'py>(
&'py self,
py: Python<'py>,
) -> Result<PyRefMut<'py, T>, PyBorrowMutError>where
T: PyClass<Frozen = False>,
pub fn try_borrow_mut<'py>(
&'py self,
py: Python<'py>,
) -> Result<PyRefMut<'py, T>, PyBorrowMutError>where
T: PyClass<Frozen = False>,
Attempts to mutably borrow the value T, returning an error if the value is currently borrowed.
The borrow lasts while the returned [PyRefMut] exists.
This is the non-panicking variant of borrow_mut.
Equivalent to self.bind(py).try_borrow_mut() - see [Bound::try_borrow_mut].
pub fn get(&self) -> &Twhere
T: PyClass<Frozen = True> + Sync,
pub fn get(&self) -> &Twhere
T: PyClass<Frozen = True> + Sync,
Provide an immutable borrow of the value T without acquiring the GIL.
This is available if the class is [frozen][macro@crate::pyclass] and Sync.
§Examples
use std::sync::atomic::{AtomicUsize, Ordering};
#[pyclass(frozen)]
struct FrozenCounter {
value: AtomicUsize,
}
let cell = Python::attach(|py| {
let counter = FrozenCounter { value: AtomicUsize::new(0) };
Py::new(py, counter).unwrap()
});
cell.get().value.fetch_add(1, Ordering::Relaxed);pub fn bind<'py>(&self, _py: Python<'py>) -> &Bound<'py, T>
pub fn bind<'py>(&self, _py: Python<'py>) -> &Bound<'py, T>
Attaches this Py to the given Python context, allowing access to further Python APIs.
pub fn bind_borrowed<'a, 'py>(&'a self, py: Python<'py>) -> Borrowed<'a, 'py, T>
pub fn bind_borrowed<'a, 'py>(&'a self, py: Python<'py>) -> Borrowed<'a, 'py, T>
Same as bind but produces a Borrowed<T> instead of a Bound<T>.
pub fn is<U>(&self, o: U) -> boolwhere
U: AsRef<Py<PyAny>>,
pub fn is<U>(&self, o: U) -> boolwhere
U: AsRef<Py<PyAny>>,
Returns whether self and other point to the same object. To compare
the equality of two objects (the == operator), use eq.
This is equivalent to the Python expression self is other.
pub fn get_refcnt(&self, _py: Python<'_>) -> isize
pub fn get_refcnt(&self, _py: Python<'_>) -> isize
Gets the reference count of the ffi::PyObject pointer.
pub fn clone_ref(&self, _py: Python<'_>) -> Py<T>
pub fn clone_ref(&self, _py: Python<'_>) -> Py<T>
Makes a clone of self.
This creates another pointer to the same object, increasing its reference count.
You should prefer using this method over Clone if you happen to be holding the GIL already.
§Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;
Python::attach(|py| {
let first: Py<PyDict> = PyDict::new(py).unbind();
let second = Py::clone_ref(&first, py);
// Both point to the same object
assert!(first.is(&second));
});pub fn is_none(&self, _py: Python<'_>) -> bool
pub fn is_none(&self, _py: Python<'_>) -> bool
Returns whether the object is considered to be None.
This is equivalent to the Python expression self is None.
pub fn is_truthy(&self, py: Python<'_>) -> Result<bool, PyErr>
pub fn is_truthy(&self, py: Python<'_>) -> Result<bool, PyErr>
Returns whether the object is considered to be true.
This applies truth value testing equivalent to the Python expression bool(self).
pub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> Result<D, PyErr>where
'py: 'a,
D: FromPyObjectBound<'a, 'py>,
pub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> Result<D, PyErr>where
'py: 'a,
D: FromPyObjectBound<'a, 'py>,
Extracts some type from the Python object.
This is a wrapper function around FromPyObject::extract().
pub fn getattr<'py, N>(
&self,
py: Python<'py>,
attr_name: N,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
pub fn getattr<'py, N>(
&self,
py: Python<'py>,
attr_name: N,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
Retrieves an attribute value.
This is equivalent to the Python expression self.attr_name.
If calling this method becomes performance-critical, the intern! macro
can be used to intern attr_name, thereby avoiding repeated temporary allocations of
Python strings.
§Example: intern!ing the attribute name
#[pyfunction]
fn version(sys: Py<PyModule>, py: Python<'_>) -> PyResult<Py<PyAny>> {
sys.getattr(py, intern!(py, "version"))
}pub fn setattr<'py, N, V>(
&self,
py: Python<'py>,
attr_name: N,
value: V,
) -> Result<(), PyErr>where
N: IntoPyObject<'py, Target = PyString>,
V: IntoPyObject<'py>,
pub fn setattr<'py, N, V>(
&self,
py: Python<'py>,
attr_name: N,
value: V,
) -> Result<(), PyErr>where
N: IntoPyObject<'py, Target = PyString>,
V: IntoPyObject<'py>,
Sets an attribute value.
This is equivalent to the Python expression self.attr_name = value.
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used to intern attr_name.
§Example: intern!ing the attribute name
#[pyfunction]
fn set_answer(ob: Py<PyAny>, py: Python<'_>) -> PyResult<()> {
ob.setattr(py, intern!(py, "answer"), 42)
}pub fn call<'py, A>(
&self,
py: Python<'py>,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Py<PyAny>, PyErr>where
A: PyCallArgs<'py>,
pub fn call<'py, A>(
&self,
py: Python<'py>,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Py<PyAny>, PyErr>where
A: PyCallArgs<'py>,
Calls the object.
This is equivalent to the Python expression self(*args, **kwargs).
pub fn call1<'py, A>(
&self,
py: Python<'py>,
args: A,
) -> Result<Py<PyAny>, PyErr>where
A: PyCallArgs<'py>,
pub fn call1<'py, A>(
&self,
py: Python<'py>,
args: A,
) -> Result<Py<PyAny>, PyErr>where
A: PyCallArgs<'py>,
Calls the object with only positional arguments.
This is equivalent to the Python expression self(*args).
pub fn call0(&self, py: Python<'_>) -> Result<Py<PyAny>, PyErr>
pub fn call0(&self, py: Python<'_>) -> Result<Py<PyAny>, PyErr>
Calls the object without arguments.
This is equivalent to the Python expression self().
pub fn call_method<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
A: PyCallArgs<'py>,
pub fn call_method<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
A: PyCallArgs<'py>,
Calls a method on the object.
This is equivalent to the Python expression self.name(*args, **kwargs).
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used to intern name.
pub fn call_method1<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
A: PyCallArgs<'py>,
pub fn call_method1<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
A: PyCallArgs<'py>,
Calls a method on the object with only positional arguments.
This is equivalent to the Python expression self.name(*args).
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used to intern name.
pub fn call_method0<'py, N>(
&self,
py: Python<'py>,
name: N,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
pub fn call_method0<'py, N>(
&self,
py: Python<'py>,
name: N,
) -> Result<Py<PyAny>, PyErr>where
N: IntoPyObject<'py, Target = PyString>,
Calls a method on the object with no arguments.
This is equivalent to the Python expression self.name().
To avoid repeated temporary allocations of Python strings, the intern!
macro can be used to intern name.
pub fn downcast_bound<'py, T>(
&self,
py: Python<'py>,
) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>where
T: PyTypeCheck,
pub fn downcast_bound<'py, T>(
&self,
py: Python<'py>,
) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>where
T: PyTypeCheck,
Downcast this Py<PyAny> to a concrete Python type or pyclass.
Note that you can often avoid casting yourself by just specifying the desired type in function or method signatures. However, manual casting is sometimes necessary.
For extracting a Rust-only type, see [Py::extract].
§Example: Downcasting to a specific Python object
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
Python::attach(|py| {
let any = PyDict::new(py).into_any().unbind();
assert!(any.downcast_bound::<PyDict>(py).is_ok());
assert!(any.downcast_bound::<PyList>(py).is_err());
});§Example: Getting a reference to a pyclass
This is useful if you want to mutate a Py<PyAny> that might actually be a pyclass.
use pyo3::prelude::*;
#[pyclass]
struct Class {
i: i32,
}
Python::attach(|py| {
let class = Py::new(py, Class { i: 0 })?.into_any();
let class_bound = class.downcast_bound::<Class>(py)?;
class_bound.borrow_mut().i += 1;
// Alternatively you can get a `PyRefMut` directly
let class_ref: PyRefMut<'_, Class> = class.extract(py)?;
assert_eq!(class_ref.i, 1);
Ok(())
})pub unsafe fn downcast_bound_unchecked<'py, T>(
&self,
py: Python<'py>,
) -> &Bound<'py, T>
pub unsafe fn downcast_bound_unchecked<'py, T>( &self, py: Python<'py>, ) -> &Bound<'py, T>
Casts the Py<PyAny> to a concrete Python object type without checking validity.
§Safety
Callers must ensure that the type is valid or risk type confusion.
pub fn cast_bound<'py, U>(
&self,
py: Python<'py>,
) -> Result<&Bound<'py, U>, DowncastError<'_, 'py>>where
U: PyTypeCheck,
pub fn cast_bound<'py, U>(
&self,
py: Python<'py>,
) -> Result<&Bound<'py, U>, DowncastError<'_, 'py>>where
U: PyTypeCheck,
Cast this Py<T> to a concrete Python type or pyclass.
Note that you can often avoid casting yourself by just specifying the desired type in function or method signatures. However, manual casting is sometimes necessary.
For extracting a Rust-only type, see [Py::extract].
§Example: Casting to a specific Python object
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
Python::attach(|py| {
let any = PyDict::new(py).into_any().unbind();
assert!(any.cast_bound::<PyDict>(py).is_ok());
assert!(any.cast_bound::<PyList>(py).is_err());
});§Example: Getting a reference to a pyclass
This is useful if you want to mutate a Py<PyAny> that might actually be a pyclass.
use pyo3::prelude::*;
#[pyclass]
struct Class {
i: i32,
}
Python::attach(|py| {
let class = Py::new(py, Class { i: 0 })?.into_any();
let class_bound = class.cast_bound::<Class>(py)?;
class_bound.borrow_mut().i += 1;
// Alternatively you can get a `PyRefMut` directly
let class_ref: PyRefMut<'_, Class> = class.extract(py)?;
assert_eq!(class_ref.i, 1);
Ok(())
})pub unsafe fn cast_bound_unchecked<'py, U>(
&self,
py: Python<'py>,
) -> &Bound<'py, U>
pub unsafe fn cast_bound_unchecked<'py, U>( &self, py: Python<'py>, ) -> &Bound<'py, U>
Casts the Py<T> to a concrete Python object type without checking validity.
§Safety
Callers must ensure that the type is valid or risk type confusion.
Trait Implementations§
Source§impl Clone for PythonObject
impl Clone for PythonObject
Source§impl Debug for PythonObject
impl Debug for PythonObject
Source§impl Deref for PythonObject
impl Deref for PythonObject
Source§impl DerefMut for PythonObject
impl DerefMut for PythonObject
Source§impl<'a> Deserialize<'a> for PythonObject
Available on crate feature serde only.
impl<'a> Deserialize<'a> for PythonObject
serde only.Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'a>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'a>,
Source§impl From<Py<PyAny>> for PythonObject
impl From<Py<PyAny>> for PythonObject
Source§impl<'py> IntoPyObject<'py> for &PythonObject
impl<'py> IntoPyObject<'py> for &PythonObject
Source§type Output = Bound<'py, <&PythonObject as IntoPyObject<'py>>::Target>
type Output = Bound<'py, <&PythonObject as IntoPyObject<'py>>::Target>
Source§fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
Source§impl<'py> IntoPyObject<'py> for PythonObject
impl<'py> IntoPyObject<'py> for PythonObject
Source§type Output = Bound<'py, <PythonObject as IntoPyObject<'py>>::Target>
type Output = Bound<'py, <PythonObject as IntoPyObject<'py>>::Target>
Source§fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
Source§impl JsonSchema for PythonObject
Available on crate feature dsl-schema only.
impl JsonSchema for PythonObject
dsl-schema only.Source§fn schema_name() -> String
fn schema_name() -> String
Source§fn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
Source§fn json_schema(generator: &mut SchemaGenerator) -> Schema
fn json_schema(generator: &mut SchemaGenerator) -> Schema
§fn is_referenceable() -> bool
fn is_referenceable() -> bool
$ref keyword. Read moreSource§impl PartialEq for PythonObject
impl PartialEq for PythonObject
Source§impl Serialize for PythonObject
Available on crate feature serde only.
impl Serialize for PythonObject
serde only.Source§impl TrySerializeToBytes for PythonObject
Available on crate feature serde only.
impl TrySerializeToBytes for PythonObject
serde only.fn try_serialize_to_bytes(&self) -> PolarsResult<Vec<u8>>
fn try_deserialize_bytes(bytes: &[u8]) -> PolarsResult<Self>
impl Eq for PythonObject
Auto Trait Implementations§
impl Freeze for PythonObject
impl !RefUnwindSafe for PythonObject
impl Send for PythonObject
impl Sync for PythonObject
impl Unpin for PythonObject
impl UnwindSafe for PythonObject
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.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§impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
§fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>
fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>
self into an owned Python object, dropping type information.§fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>
fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>
self into an owned Python object, dropping type information and unbinding it
from the 'py lifetime.§fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>
fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>
self into a Python object. Read more