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
impl PyObject
Sourcepub 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 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_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 })?.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(())
})
Sourcepub 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 PyObject to a concrete Python object type without checking validity.
§Safety
Callers must ensure that the type is valid or risk type confusion.
Source§impl<T> Py<T>where
T: PyClass,
impl<T> Py<T>where
T: PyClass,
Sourcepub fn new(
py: Python<'_>,
value: impl Into<PyClassInitializer<T>>,
) -> PyResult<Py<T>>
pub fn new( py: Python<'_>, value: impl Into<PyClassInitializer<T>>, ) -> PyResult<Py<T>>
Creates a new instance Py<T>
of a #[pyclass]
on the Python heap.
§Examples
use pyo3::prelude::*;
#[pyclass]
struct Foo {/* fields omitted */}
let foo = Python::with_gil(|py| -> PyResult<_> {
let foo: Py<Foo> = Py::new(py, Foo {})?;
Ok(foo)
})?;
Source§impl<T> Py<T>
impl<T> Py<T>
Sourcepub 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.
Source§impl<T> Py<T>where
T: PyClass,
impl<T> Py<T>where
T: PyClass,
Sourcepub 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
is available.
Equivalent to self.bind(py).borrow()
- see Bound::borrow
.
§Examples
#[pyclass]
struct Foo {
inner: u8,
}
Python::with_gil(|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
.
Sourcepub 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::with_gil(|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
.
Sourcepub 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
is available.
Equivalent to self.bind(py).try_borrow()
- see Bound::try_borrow
.
Sourcepub 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
.
Sourcepub fn get(&self) -> &T
pub fn get(&self) -> &T
Provide an immutable borrow of the value T
without acquiring the GIL.
This is available if the class is frozen
and Sync
.
§Examples
use std::sync::atomic::{AtomicUsize, Ordering};
#[pyclass(frozen)]
struct FrozenCounter {
value: AtomicUsize,
}
let cell = Python::with_gil(|py| {
let counter = FrozenCounter { value: AtomicUsize::new(0) };
Py::new(py, counter).unwrap()
});
cell.get().value.fetch_add(1, Ordering::Relaxed);
Source§impl<T> Py<T>
impl<T> Py<T>
Sourcepub 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.
Sourcepub fn into_bound(self, py: Python<'_>) -> Bound<'_, T>
pub fn into_bound(self, py: Python<'_>) -> Bound<'_, T>
Same as bind
but takes ownership of self
.
Sourcepub 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>
.
Sourcepub fn is<U: AsPyPointer>(&self, o: &U) -> bool
pub fn is<U: AsPyPointer>(&self, o: &U) -> bool
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
.
Sourcepub fn get_refcnt(&self, _py: Python<'_>) -> isize
pub fn get_refcnt(&self, _py: Python<'_>) -> isize
Gets the reference count of the ffi::PyObject
pointer.
Sourcepub 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::with_gil(|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));
});
Sourcepub fn drop_ref(self, py: Python<'_>)
pub fn drop_ref(self, py: Python<'_>)
Drops self
and immediately decreases its reference count.
This method is a micro-optimisation over Drop
if you happen to be holding the GIL
already.
Note that if you are using Bound
, you do not need to use Self::drop_ref
since
Bound
guarantees that the GIL is held.
§Examples
use pyo3::prelude::*;
use pyo3::types::PyDict;
Python::with_gil(|py| {
let object: Py<PyDict> = PyDict::new(py).unbind();
// some usage of object
object.drop_ref(py);
});
Sourcepub 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
.
Sourcepub fn is_truthy(&self, py: Python<'_>) -> PyResult<bool>
pub fn is_truthy(&self, py: Python<'_>) -> PyResult<bool>
Returns whether the object is considered to be true.
This applies truth value testing equivalent to the Python expression bool(self)
.
Sourcepub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> PyResult<D>where
D: FromPyObjectBound<'a, 'py>,
'py: 'a,
pub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> PyResult<D>where
D: FromPyObjectBound<'a, 'py>,
'py: 'a,
Extracts some type from the Python object.
This is a wrapper function around FromPyObject::extract()
.
Sourcepub fn getattr<'py, N>(
&self,
py: Python<'py>,
attr_name: N,
) -> PyResult<PyObject>where
N: IntoPyObject<'py, Target = PyString>,
pub fn getattr<'py, N>(
&self,
py: Python<'py>,
attr_name: N,
) -> PyResult<PyObject>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<PyObject> {
sys.getattr(py, intern!(py, "version"))
}
Sourcepub fn setattr<'py, N, V>(
&self,
py: Python<'py>,
attr_name: N,
value: V,
) -> PyResult<()>
pub fn setattr<'py, N, V>( &self, py: Python<'py>, attr_name: N, value: V, ) -> PyResult<()>
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: PyObject, py: Python<'_>) -> PyResult<()> {
ob.setattr(py, intern!(py, "answer"), 42)
}
Sourcepub fn call<'py, A>(
&self,
py: Python<'py>,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<PyObject>where
A: IntoPyObject<'py, Target = PyTuple>,
pub fn call<'py, A>(
&self,
py: Python<'py>,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<PyObject>where
A: IntoPyObject<'py, Target = PyTuple>,
Calls the object.
This is equivalent to the Python expression self(*args, **kwargs)
.
Sourcepub fn call_bound(
&self,
py: Python<'_>,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyObject>
👎Deprecated since 0.23.0: renamed to Py::call
pub fn call_bound( &self, py: Python<'_>, args: impl IntoPy<Py<PyTuple>>, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<PyObject>
Py::call
Deprecated name for Py::call
.
Sourcepub fn call1<'py, N>(&self, py: Python<'py>, args: N) -> PyResult<PyObject>where
N: IntoPyObject<'py, Target = PyTuple>,
pub fn call1<'py, N>(&self, py: Python<'py>, args: N) -> PyResult<PyObject>where
N: IntoPyObject<'py, Target = PyTuple>,
Calls the object with only positional arguments.
This is equivalent to the Python expression self(*args)
.
Sourcepub fn call0(&self, py: Python<'_>) -> PyResult<PyObject>
pub fn call0(&self, py: Python<'_>) -> PyResult<PyObject>
Calls the object without arguments.
This is equivalent to the Python expression self()
.
Sourcepub fn call_method<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
kwargs: Option<&Bound<'py, PyDict>>,
) -> PyResult<PyObject>
pub fn call_method<'py, N, A>( &self, py: Python<'py>, name: N, args: A, kwargs: Option<&Bound<'py, PyDict>>, ) -> PyResult<PyObject>
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
.
Sourcepub fn call_method_bound<N, A>(
&self,
py: Python<'_>,
name: N,
args: A,
kwargs: Option<&Bound<'_, PyDict>>,
) -> PyResult<PyObject>
👎Deprecated since 0.23.0: renamed to Py::call_method
pub fn call_method_bound<N, A>( &self, py: Python<'_>, name: N, args: A, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<PyObject>
Py::call_method
Deprecated name for Py::call_method
.
Sourcepub fn call_method1<'py, N, A>(
&self,
py: Python<'py>,
name: N,
args: A,
) -> PyResult<PyObject>
pub fn call_method1<'py, N, A>( &self, py: Python<'py>, name: N, args: A, ) -> PyResult<PyObject>
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
.
Sourcepub fn call_method0<'py, N>(
&self,
py: Python<'py>,
name: N,
) -> PyResult<PyObject>where
N: IntoPyObject<'py, Target = PyString>,
pub fn call_method0<'py, N>(
&self,
py: Python<'py>,
name: N,
) -> PyResult<PyObject>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
.
Sourcepub unsafe fn from_owned_ptr_or_opt(
_py: Python<'_>,
ptr: *mut PyObject,
) -> Option<Self>
pub unsafe fn from_owned_ptr_or_opt( _py: Python<'_>, ptr: *mut PyObject, ) -> Option<Self>
Create a Py<T>
instance by taking ownership of the given FFI pointer.
If ptr
is null then None
is returned.
§Safety
If non-null, ptr
must be a pointer to a Python object of type T.
Sourcepub unsafe fn from_borrowed_ptr_or_err(
py: Python<'_>,
ptr: *mut PyObject,
) -> PyResult<Self>
pub unsafe fn from_borrowed_ptr_or_err( py: Python<'_>, ptr: *mut PyObject, ) -> PyResult<Self>
Create a Py<T>
instance by creating a new reference from the given FFI pointer.
If ptr
is null then the current Python exception is fetched as a PyErr
.
§Safety
ptr
must be a pointer to a Python object of type T.
Trait Implementations§
Source§impl<T> AsPyPointer for Py<T>
impl<T> AsPyPointer for Py<T>
Source§impl<T> Clone for Py<T>
If the GIL is held this increments self
’s reference count.
Otherwise, it will panic.
impl<T> Clone for Py<T>
If the GIL is held this increments self
’s reference count.
Otherwise, it will panic.
Only available if the py-clone
feature is enabled.
Source§impl<'de, T> Deserialize<'de> for Py<T>
impl<'de, T> Deserialize<'de> for Py<T>
Source§fn deserialize<D>(deserializer: D) -> Result<Py<T>, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Py<T>, D::Error>where
D: Deserializer<'de>,
Source§impl<T> Display for Py<T>where
T: PyTypeInfo,
impl<T> Display for Py<T>where
T: PyTypeInfo,
Source§impl<T> Drop for Py<T>
Dropping a Py
instance decrements the reference count
on the object by one if the GIL is held.
impl<T> Drop for Py<T>
Dropping a Py
instance decrements the reference count
on the object by one if the GIL is held.
Otherwise and by default, this registers the underlying pointer to have its reference count decremented the next time PyO3 acquires the GIL.
However, if the pyo3_disable_reference_pool
conditional compilation flag
is enabled, it will abort the process.