pyo3

Type Alias PyObject

Source
pub type PyObject = Py<PyAny>;
Expand description

A commonly-used alias for Py<PyAny>.

This is an owned reference a Python object without any type information. This value can also be safely sent between threads.

See the documentation for Py.

Aliased Type§

struct PyObject(/* private fields */);

Implementations§

Source§

impl PyObject

Source

pub fn downcast_bound<'py, T>( &self, py: Python<'py>, ) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>
where T: PyTypeCheck,

Downcast this PyObject to a concrete Python type or pyclass.

Note that you can often avoid downcasting yourself by just specifying the desired type in function or method signatures. However, manual downcasting 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::with_gil(|py| {
    let any: PyObject = PyDict::new_bound(py).into();

    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 PyObject that might actually be a pyclass.

use pyo3::prelude::*;

#[pyclass]
struct Class {
    i: i32,
}

Python::with_gil(|py| {
    let class: PyObject = Py::new(py, Class { i: 0 }).unwrap().into_py(py);

    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(())
})
Source

pub unsafe fn downcast_bound_unchecked<'py, T>( &self, py: Python<'py>, ) -> &Bound<'py, T>

Casts the PyObject 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<T> From<Bound<'_, T>> for PyObject
where T: AsRef<PyAny>,

Source§

fn from(other: Bound<'_, T>) -> Self

Converts to this type from the input type.
Source§

impl<T> From<Py<T>> for PyObject
where T: AsRef<PyAny>,

Source§

fn from(other: Py<T>) -> Self

Converts to this type from the input type.