PythonObject

Struct PythonObject 

Source
pub struct PythonObject(pub Py<PyAny>);
Available on crate feature python only.
Expand description

Wrapper around PyObject from pyo3 with additional trait impls.

Tuple Fields§

§0: Py<PyAny>

Implementations§

Source§

impl PythonObject

Source

pub fn serialize_with_pyversion<T, S>( value: &T, serializer: S, ) -> Result<S::Ok, S::Error>

Available on crate feature serde only.
Source

pub fn deserialize_with_pyversion<'de, T, D>(d: D) -> Result<T, D::Error>
where T: From<PythonObject>, D: Deserializer<'de>,

Available on crate feature serde only.

Methods from Deref<Target = Py<PyAny>>§

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>

Helper to cast to Py<PyAny>.

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>,

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>

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>,

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) -> &T
where 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>

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>

Same as bind but produces a Borrowed<T> instead of a Bound<T>.

pub fn is<U>(&self, o: U) -> bool
where 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

Gets the reference count of the ffi::PyObject pointer.

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

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>

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>,

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>,

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>,

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>,

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>,

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>

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>,

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>,

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>,

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,

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>

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,

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>

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

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PythonObject

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for PythonObject

Source§

type Target = Py<PyAny>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for PythonObject

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<'a> Deserialize<'a> for PythonObject

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'a>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<Py<PyAny>> for PythonObject

Source§

fn from(value: Py<PyAny>) -> Self

Converts to this type from the input type.
Source§

impl<'py> IntoPyObject<'py> for &PythonObject

Source§

type Target = PyAny

The Python output type
Source§

type Output = Bound<'py, <&PythonObject as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

The type returned in the event of a conversion error.
Source§

fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>

Performs the conversion.
Source§

impl<'py> IntoPyObject<'py> for PythonObject

Source§

type Target = PyAny

The Python output type
Source§

type Output = Bound<'py, <PythonObject as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

The type returned in the event of a conversion error.
Source§

fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>

Performs the conversion.
Source§

impl JsonSchema for PythonObject

Available on crate feature dsl-schema only.
Source§

fn schema_name() -> String

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
§

fn is_referenceable() -> bool

Whether JSON Schemas generated for this type should be re-used where possible using the $ref keyword. Read more
Source§

impl PartialEq for PythonObject

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for PythonObject

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TrySerializeToBytes for PythonObject

Available on crate feature serde only.
Source§

fn try_serialize_to_bytes(&self) -> PolarsResult<Vec<u8>>

Source§

fn try_deserialize_bytes(bytes: &[u8]) -> PolarsResult<Self>

Source§

impl Eq for PythonObject

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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 T
where T: IntoPyObject<'py>,

§

fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>

Converts self into an owned Python object, dropping type information.
§

fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>

Converts 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>

Converts self into a Python object. Read more
Source§

impl<T> Key for T
where T: Clone,

Source§

fn align() -> usize

The alignment necessary for the key. Must return a power of two.
Source§

fn size(&self) -> usize

The size of the key in bytes.
Source§

unsafe fn init(&self, ptr: *mut u8)

Initialize the key in the given memory location. Read more
Source§

unsafe fn get<'a>(ptr: *const u8) -> &'a T

Get a reference to the key from the given memory location. Read more
Source§

unsafe fn drop_in_place(ptr: *mut u8)

Drop the key in place. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PyErrArguments for T
where T: for<'py> IntoPyObject<'py> + Send + Sync,

§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<T> Ungil for T
where T: Send,