Type Definition pyo3::prelude::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.

Implementations§

source§

impl PyObject

source

pub fn downcast<'p, T>(
&'p self,
py: Python<'p>
) -> Result<&T, PyDowncastError<'_>>where
T: PyTryFrom<'p>,

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(py).into();

    assert!(any.downcast::<PyDict>(py).is_ok());
    assert!(any.downcast::<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_cell: &PyCell<Class> = class.downcast(py)?;

    class_cell.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_unchecked<'p, T>(&'p self, py: Python<'p>) -> &Twhere
T: PyTryFrom<'p>,

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.

source

pub fn cast_as<'p, D>(
&'p self,
py: Python<'p>
) -> Result<&'p D, PyDowncastError<'_>>where
D: PyTryFrom<'p>,

👎Deprecated since 0.18.0: use downcast() instead

Casts the PyObject to a concrete Python object type.

Trait Implementations§

source§

impl<T> From<&T> for PyObjectwhere
T: AsPyPointer + PyNativeType,

source§

fn from(obj: &T) -> Self

Converts to this type from the input type.
source§

impl<T> From<Py<T>> for PyObjectwhere
T: AsRef<PyAny>,

source§

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

Converts to this type from the input type.