Type Alias 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.

Aliased Type§

struct PyObject(/* private fields */);



impl PyObject


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();

§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::*;

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);

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.


Callers must ensure that the type is valid or risk type confusion.

Trait Implementations§


impl<T> From<Bound<'_, T>> for PyObject
where T: AsRef<PyAny>,


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

Converts to this type from the input type.

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


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

Converts to this type from the input type.