2024-05-01 10:57:03 +00:00
|
|
|
use crate::err::{self, PyErr, PyResult};
|
2024-03-03 07:00:59 +00:00
|
|
|
use crate::impl_::pycell::PyClassObject;
|
2024-03-03 14:47:25 +00:00
|
|
|
use crate::pycell::{PyBorrowError, PyBorrowMutError};
|
2023-05-16 19:48:59 +00:00
|
|
|
use crate::pyclass::boolean_struct::{False, True};
|
2024-05-12 18:30:08 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2023-11-27 20:19:44 +00:00
|
|
|
use crate::type_object::HasPyGilRef;
|
2024-02-18 03:07:48 +00:00
|
|
|
use crate::types::{any::PyAnyMethods, string::PyStringMethods, typeobject::PyTypeMethods};
|
2024-02-22 22:38:42 +00:00
|
|
|
use crate::types::{DerefToPyAny, PyDict, PyString, PyTuple};
|
2020-02-03 13:25:16 +00:00
|
|
|
use crate::{
|
2024-02-18 01:11:43 +00:00
|
|
|
ffi, AsPyPointer, DowncastError, FromPyObject, IntoPy, PyAny, PyClass, PyClassInitializer,
|
|
|
|
PyRef, PyRefMut, PyTypeInfo, Python, ToPyObject,
|
2020-02-03 13:25:16 +00:00
|
|
|
};
|
2023-11-27 20:19:44 +00:00
|
|
|
use crate::{gil, PyTypeCheck};
|
2019-02-08 04:58:44 +00:00
|
|
|
use std::marker::PhantomData;
|
2024-02-01 09:27:44 +00:00
|
|
|
use std::mem::ManuallyDrop;
|
2023-09-10 13:51:19 +00:00
|
|
|
use std::ops::Deref;
|
2019-02-01 13:01:18 +00:00
|
|
|
use std::ptr::NonNull;
|
2017-05-29 04:19:29 +00:00
|
|
|
|
2020-03-17 09:04:03 +00:00
|
|
|
/// Types that are built into the Python interpreter.
|
2018-11-12 13:20:40 +00:00
|
|
|
///
|
2020-03-17 19:06:09 +00:00
|
|
|
/// PyO3 is designed in a way that all references to those types are bound
|
2020-03-17 09:04:03 +00:00
|
|
|
/// to the GIL, which is why you can get a token from all references of those
|
|
|
|
/// types.
|
2021-12-03 23:29:02 +00:00
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// This trait must only be implemented for types which cannot be accessed without the GIL.
|
2024-05-12 18:30:08 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2019-02-25 14:15:13 +00:00
|
|
|
pub unsafe trait PyNativeType: Sized {
|
2023-12-14 18:35:06 +00:00
|
|
|
/// The form of this which is stored inside a `Py<T>` smart pointer.
|
|
|
|
type AsRefSource: HasPyGilRef<AsRefTarget = Self>;
|
|
|
|
|
2023-12-23 21:48:04 +00:00
|
|
|
/// Cast `&self` to a `Borrowed` smart pointer.
|
|
|
|
///
|
|
|
|
/// `Borrowed<T>` implements `Deref<Target=Bound<T>>`, so can also be used in locations
|
|
|
|
/// where `Bound<T>` is expected.
|
|
|
|
///
|
|
|
|
/// This is available as a migration tool to adjust code from the deprecated "GIL Refs"
|
|
|
|
/// API to the `Bound` smart pointer API.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-23 21:48:04 +00:00
|
|
|
fn as_borrowed(&self) -> Borrowed<'_, '_, Self::AsRefSource> {
|
|
|
|
// Safety: &'py Self is expected to be a Python pointer,
|
|
|
|
// so has the same layout as Borrowed<'py, 'py, T>
|
2024-02-01 09:27:44 +00:00
|
|
|
Borrowed(
|
|
|
|
unsafe { NonNull::new_unchecked(self as *const Self as *mut _) },
|
|
|
|
PhantomData,
|
|
|
|
self.py(),
|
|
|
|
)
|
2023-12-23 21:48:04 +00:00
|
|
|
}
|
|
|
|
|
2021-07-04 11:32:40 +00:00
|
|
|
/// Returns a GIL marker constrained to the lifetime of this type.
|
2021-08-01 21:41:32 +00:00
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
fn py(&self) -> Python<'_> {
|
2019-02-25 14:15:13 +00:00
|
|
|
unsafe { Python::assume_gil_acquired() }
|
|
|
|
}
|
2020-05-01 16:09:10 +00:00
|
|
|
/// Cast `&PyAny` to `&Self` without no type checking.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
2020-05-02 04:00:12 +00:00
|
|
|
/// `obj` must have the same layout as `*const ffi::PyObject` and must be
|
|
|
|
/// an instance of a type corresponding to `Self`.
|
2020-05-01 16:09:10 +00:00
|
|
|
unsafe fn unchecked_downcast(obj: &PyAny) -> &Self {
|
|
|
|
&*(obj.as_ptr() as *const Self)
|
|
|
|
}
|
2017-05-29 04:19:29 +00:00
|
|
|
}
|
2017-06-04 00:27:26 +00:00
|
|
|
|
2023-09-10 13:51:19 +00:00
|
|
|
/// A GIL-attached equivalent to `Py`.
|
|
|
|
#[repr(transparent)]
|
2023-12-21 12:20:33 +00:00
|
|
|
pub struct Bound<'py, T>(Python<'py>, ManuallyDrop<Py<T>>);
|
2023-09-10 13:51:19 +00:00
|
|
|
|
2023-11-28 14:45:45 +00:00
|
|
|
impl<'py, T> Bound<'py, T>
|
|
|
|
where
|
|
|
|
T: PyClass,
|
|
|
|
{
|
|
|
|
/// Creates a new instance `Bound<T>` of a `#[pyclass]` on the Python heap.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
///
|
|
|
|
/// #[pyclass]
|
|
|
|
/// struct Foo {/* fields omitted */}
|
|
|
|
///
|
|
|
|
/// # fn main() -> PyResult<()> {
|
2024-05-11 14:48:45 +00:00
|
|
|
/// let foo: Py<Foo> = Python::with_gil(|py| -> PyResult<_> {
|
2023-11-28 14:45:45 +00:00
|
|
|
/// let foo: Bound<'_, Foo> = Bound::new(py, Foo {})?;
|
|
|
|
/// Ok(foo.into())
|
|
|
|
/// })?;
|
2024-05-11 14:48:45 +00:00
|
|
|
/// # Python::with_gil(move |_py| drop(foo));
|
2023-11-28 14:45:45 +00:00
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
pub fn new(
|
|
|
|
py: Python<'py>,
|
|
|
|
value: impl Into<PyClassInitializer<T>>,
|
|
|
|
) -> PyResult<Bound<'py, T>> {
|
2024-03-03 07:00:59 +00:00
|
|
|
value.into().create_class_object(py)
|
2023-11-28 14:45:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<'py> Bound<'py, PyAny> {
|
2024-01-16 21:34:13 +00:00
|
|
|
/// Constructs a new `Bound<'py, PyAny>` from a pointer. Panics if `ptr` is null.
|
2023-12-23 14:26:02 +00:00
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
2024-01-16 21:34:13 +00:00
|
|
|
/// - `ptr` must be a valid pointer to a Python object
|
|
|
|
/// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2024-01-16 21:34:13 +00:00
|
|
|
pub unsafe fn from_owned_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
|
2023-09-10 13:51:19 +00:00
|
|
|
Self(py, ManuallyDrop::new(Py::from_owned_ptr(py, ptr)))
|
|
|
|
}
|
|
|
|
|
2024-02-18 22:03:43 +00:00
|
|
|
/// Constructs a new `Bound<'py, PyAny>` from a pointer. Returns `None` if `ptr` is null.
|
2023-12-23 14:26:02 +00:00
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
2024-01-16 21:34:13 +00:00
|
|
|
/// - `ptr` must be a valid pointer to a Python object, or null
|
|
|
|
/// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-01-16 21:34:13 +00:00
|
|
|
pub unsafe fn from_owned_ptr_or_opt(py: Python<'py>, ptr: *mut ffi::PyObject) -> Option<Self> {
|
2023-12-23 14:26:02 +00:00
|
|
|
Py::from_owned_ptr_or_opt(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
|
|
|
|
}
|
2023-09-10 13:51:19 +00:00
|
|
|
|
2024-01-16 21:34:13 +00:00
|
|
|
/// Constructs a new `Bound<'py, PyAny>` from a pointer. Returns an `Err` by calling `PyErr::fetch`
|
|
|
|
/// if `ptr` is null.
|
2023-12-23 14:26:02 +00:00
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
2024-01-16 21:34:13 +00:00
|
|
|
/// - `ptr` must be a valid pointer to a Python object, or null
|
|
|
|
/// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-01-16 21:34:13 +00:00
|
|
|
pub unsafe fn from_owned_ptr_or_err(
|
2023-09-10 13:51:19 +00:00
|
|
|
py: Python<'py>,
|
|
|
|
ptr: *mut ffi::PyObject,
|
|
|
|
) -> PyResult<Self> {
|
|
|
|
Py::from_owned_ptr_or_err(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
|
|
|
|
}
|
2024-02-16 00:36:11 +00:00
|
|
|
|
2024-02-18 22:03:43 +00:00
|
|
|
/// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference.
|
|
|
|
/// Panics if `ptr` is null.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2024-02-18 22:03:43 +00:00
|
|
|
pub unsafe fn from_borrowed_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
|
|
|
|
Self(py, ManuallyDrop::new(Py::from_borrowed_ptr(py, ptr)))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference.
|
|
|
|
/// Returns `None` if `ptr` is null.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object, or null
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-02-18 22:03:43 +00:00
|
|
|
pub unsafe fn from_borrowed_ptr_or_opt(
|
|
|
|
py: Python<'py>,
|
|
|
|
ptr: *mut ffi::PyObject,
|
|
|
|
) -> Option<Self> {
|
|
|
|
Py::from_borrowed_ptr_or_opt(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference.
|
|
|
|
/// Returns an `Err` by calling `PyErr::fetch` if `ptr` is null.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object, or null
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-02-18 22:03:43 +00:00
|
|
|
pub unsafe fn from_borrowed_ptr_or_err(
|
|
|
|
py: Python<'py>,
|
|
|
|
ptr: *mut ffi::PyObject,
|
|
|
|
) -> PyResult<Self> {
|
|
|
|
Py::from_borrowed_ptr_or_err(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
|
|
|
|
}
|
|
|
|
|
2024-02-16 00:36:11 +00:00
|
|
|
/// This slightly strange method is used to obtain `&Bound<PyAny>` from a pointer in macro code
|
|
|
|
/// where we need to constrain the lifetime `'a` safely.
|
|
|
|
///
|
|
|
|
/// Note that `'py` is required to outlive `'a` implicitly by the nature of the fact that
|
|
|
|
/// `&'a Bound<'py>` means that `Bound<'py>` exists for at least the lifetime `'a`.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object for the lifetime `'a`. The `ptr` can
|
|
|
|
/// be either a borrowed reference or an owned reference, it does not matter, as this is
|
|
|
|
/// just `&Bound` there will never be any ownership transfer.
|
|
|
|
#[inline]
|
|
|
|
pub(crate) unsafe fn ref_from_ptr<'a>(
|
|
|
|
_py: Python<'py>,
|
|
|
|
ptr: &'a *mut ffi::PyObject,
|
|
|
|
) -> &'a Self {
|
|
|
|
&*(ptr as *const *mut ffi::PyObject).cast::<Bound<'py, PyAny>>()
|
|
|
|
}
|
2024-02-22 23:06:55 +00:00
|
|
|
|
|
|
|
/// Variant of the above which returns `None` for null pointers.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object for the lifetime `'a, or null.
|
|
|
|
#[inline]
|
|
|
|
pub(crate) unsafe fn ref_from_ptr_or_opt<'a>(
|
|
|
|
_py: Python<'py>,
|
|
|
|
ptr: &'a *mut ffi::PyObject,
|
|
|
|
) -> &'a Option<Self> {
|
|
|
|
&*(ptr as *const *mut ffi::PyObject).cast::<Option<Bound<'py, PyAny>>>()
|
|
|
|
}
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
|
2023-11-28 14:45:45 +00:00
|
|
|
impl<'py, T> Bound<'py, T>
|
|
|
|
where
|
|
|
|
T: PyClass,
|
|
|
|
{
|
|
|
|
/// 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.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
/// #
|
|
|
|
/// #[pyclass]
|
|
|
|
/// struct Foo {
|
|
|
|
/// inner: u8,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// # fn main() -> PyResult<()> {
|
|
|
|
/// Python::with_gil(|py| -> PyResult<()> {
|
|
|
|
/// let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
|
|
|
|
/// let inner: &u8 = &foo.borrow().inner;
|
|
|
|
///
|
|
|
|
/// assert_eq!(*inner, 73);
|
|
|
|
/// Ok(())
|
|
|
|
/// })?;
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
|
|
|
|
/// [`try_borrow`](#method.try_borrow).
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2024-02-27 18:56:22 +00:00
|
|
|
pub fn borrow(&self) -> PyRef<'py, T> {
|
|
|
|
PyRef::borrow(self)
|
2023-11-28 14:45:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Mutably borrows the value `T`.
|
|
|
|
///
|
|
|
|
/// This borrow lasts while the returned [`PyRefMut`] exists.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
/// #
|
|
|
|
/// #[pyclass]
|
|
|
|
/// struct Foo {
|
|
|
|
/// inner: u8,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// # fn main() -> PyResult<()> {
|
|
|
|
/// Python::with_gil(|py| -> PyResult<()> {
|
|
|
|
/// let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
|
|
|
|
/// foo.borrow_mut().inner = 35;
|
|
|
|
///
|
|
|
|
/// assert_eq!(foo.borrow().inner, 35);
|
|
|
|
/// Ok(())
|
|
|
|
/// })?;
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// Panics if the value is currently borrowed. For a non-panicking variant, use
|
|
|
|
/// [`try_borrow_mut`](#method.try_borrow_mut).
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2024-02-27 18:56:22 +00:00
|
|
|
pub fn borrow_mut(&self) -> PyRefMut<'py, T>
|
2023-11-28 14:45:45 +00:00
|
|
|
where
|
|
|
|
T: PyClass<Frozen = False>,
|
|
|
|
{
|
2024-02-27 18:56:22 +00:00
|
|
|
PyRefMut::borrow(self)
|
2023-11-28 14:45:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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`](#method.borrow).
|
|
|
|
///
|
|
|
|
/// For frozen classes, the simpler [`get`][Self::get] is available.
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-02-27 18:56:22 +00:00
|
|
|
pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError> {
|
|
|
|
PyRef::try_borrow(self)
|
2023-11-28 14:45:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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`](#method.borrow_mut).
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-02-27 18:56:22 +00:00
|
|
|
pub fn try_borrow_mut(&self) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
|
2023-11-28 14:45:45 +00:00
|
|
|
where
|
|
|
|
T: PyClass<Frozen = False>,
|
|
|
|
{
|
2024-02-27 18:56:22 +00:00
|
|
|
PyRefMut::try_borrow(self)
|
2023-11-28 14:45:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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};
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
///
|
|
|
|
/// #[pyclass(frozen)]
|
|
|
|
/// struct FrozenCounter {
|
|
|
|
/// value: AtomicUsize,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// Python::with_gil(|py| {
|
|
|
|
/// let counter = FrozenCounter { value: AtomicUsize::new(0) };
|
|
|
|
///
|
|
|
|
/// let py_counter = Bound::new(py, counter).unwrap();
|
|
|
|
///
|
|
|
|
/// py_counter.get().value.fetch_add(1, Ordering::Relaxed);
|
|
|
|
/// });
|
|
|
|
/// ```
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2023-11-28 14:45:45 +00:00
|
|
|
pub fn get(&self) -> &T
|
|
|
|
where
|
|
|
|
T: PyClass<Frozen = True> + Sync,
|
|
|
|
{
|
2024-03-03 07:00:59 +00:00
|
|
|
self.1.get()
|
2023-11-28 14:45:45 +00:00
|
|
|
}
|
|
|
|
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-03-03 07:00:59 +00:00
|
|
|
pub(crate) fn get_class_object(&self) -> &PyClassObject<T> {
|
|
|
|
self.1.get_class_object()
|
2023-11-28 14:45:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<'py, T> std::fmt::Debug for Bound<'py, T> {
|
2023-09-10 13:51:19 +00:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
|
|
|
let any = self.as_any();
|
|
|
|
python_format(any, any.repr(), f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<'py, T> std::fmt::Display for Bound<'py, T> {
|
2023-09-10 13:51:19 +00:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
|
|
|
let any = self.as_any();
|
|
|
|
python_format(any, any.str(), f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn python_format(
|
2023-12-21 12:04:45 +00:00
|
|
|
any: &Bound<'_, PyAny>,
|
|
|
|
format_result: PyResult<Bound<'_, PyString>>,
|
2023-09-10 13:51:19 +00:00
|
|
|
f: &mut std::fmt::Formatter<'_>,
|
|
|
|
) -> Result<(), std::fmt::Error> {
|
|
|
|
match format_result {
|
2023-12-24 14:49:43 +00:00
|
|
|
Result::Ok(s) => return f.write_str(&s.to_string_lossy()),
|
|
|
|
Result::Err(err) => err.write_unraisable_bound(any.py(), Some(any)),
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
match any.get_type().name() {
|
|
|
|
Result::Ok(name) => std::write!(f, "<unprintable {} object>", name),
|
|
|
|
Result::Err(_err) => f.write_str("<unprintable object>"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-22 22:38:42 +00:00
|
|
|
// The trait bound is needed to avoid running into the auto-deref recursion
|
|
|
|
// limit (error[E0055]), because `Bound<PyAny>` would deref into itself. See:
|
|
|
|
// https://github.com/rust-lang/rust/issues/19509
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<'py, T> Deref for Bound<'py, T>
|
2023-09-10 13:51:19 +00:00
|
|
|
where
|
2024-02-22 22:38:42 +00:00
|
|
|
T: DerefToPyAny,
|
2023-09-10 13:51:19 +00:00
|
|
|
{
|
2023-12-21 12:04:45 +00:00
|
|
|
type Target = Bound<'py, PyAny>;
|
2023-09-10 13:51:19 +00:00
|
|
|
|
|
|
|
#[inline]
|
2023-12-21 12:04:45 +00:00
|
|
|
fn deref(&self) -> &Bound<'py, PyAny> {
|
2023-09-10 13:51:19 +00:00
|
|
|
self.as_any()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-22 22:38:42 +00:00
|
|
|
impl<'py, T> AsRef<Bound<'py, PyAny>> for Bound<'py, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-21 12:04:45 +00:00
|
|
|
fn as_ref(&self) -> &Bound<'py, PyAny> {
|
2023-09-10 13:51:19 +00:00
|
|
|
self.as_any()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<T> Clone for Bound<'_, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-09-10 13:51:19 +00:00
|
|
|
fn clone(&self) -> Self {
|
|
|
|
Self(self.0, ManuallyDrop::new(self.1.clone_ref(self.0)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<T> Drop for Bound<'_, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-09-10 13:51:19 +00:00
|
|
|
fn drop(&mut self) {
|
2024-02-01 09:27:44 +00:00
|
|
|
unsafe { ffi::Py_DECREF(self.as_ptr()) }
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<'py, T> Bound<'py, T> {
|
2023-09-10 13:51:19 +00:00
|
|
|
/// Returns the GIL token associated with this object.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-09-10 13:51:19 +00:00
|
|
|
pub fn py(&self) -> Python<'py> {
|
|
|
|
self.0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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.
|
|
|
|
#[inline]
|
|
|
|
pub fn as_ptr(&self) -> *mut ffi::PyObject {
|
|
|
|
self.1.as_ptr()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns an owned raw FFI pointer represented by self.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// The reference is owned; when finished the caller should either transfer ownership
|
|
|
|
/// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)).
|
|
|
|
#[inline]
|
|
|
|
pub fn into_ptr(self) -> *mut ffi::PyObject {
|
2024-02-01 09:27:44 +00:00
|
|
|
ManuallyDrop::new(self).as_ptr()
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
|
2023-11-28 10:40:37 +00:00
|
|
|
/// Helper to cast to `Bound<'py, PyAny>`.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-11-28 10:40:37 +00:00
|
|
|
pub fn as_any(&self) -> &Bound<'py, PyAny> {
|
|
|
|
// Safety: all Bound<T> have the same memory layout, and all Bound<T> are valid
|
|
|
|
// Bound<PyAny>, so pointer casting is valid.
|
|
|
|
unsafe { &*(self as *const Self).cast::<Bound<'py, PyAny>>() }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Helper to cast to `Bound<'py, PyAny>`, transferring ownership.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-11-28 10:40:37 +00:00
|
|
|
pub fn into_any(self) -> Bound<'py, PyAny> {
|
|
|
|
// Safety: all Bound<T> are valid Bound<PyAny>
|
2024-02-01 09:07:36 +00:00
|
|
|
Bound(self.0, ManuallyDrop::new(self.unbind().into_any()))
|
2023-11-28 10:40:37 +00:00
|
|
|
}
|
|
|
|
|
2023-12-24 13:48:13 +00:00
|
|
|
/// Casts this `Bound<T>` to a `Borrowed<T>` smart pointer.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-24 13:48:13 +00:00
|
|
|
pub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T> {
|
|
|
|
Borrowed(
|
|
|
|
unsafe { NonNull::new_unchecked(self.as_ptr()) },
|
|
|
|
PhantomData,
|
|
|
|
self.py(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2023-12-26 13:16:41 +00:00
|
|
|
/// Removes the connection for this `Bound<T>` from the GIL, allowing
|
|
|
|
/// it to cross thread boundaries.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-26 13:16:41 +00:00
|
|
|
pub fn unbind(self) -> Py<T> {
|
|
|
|
// Safety: the type T is known to be correct and the ownership of the
|
|
|
|
// pointer is transferred to the new Py<T> instance.
|
2024-02-01 09:27:44 +00:00
|
|
|
let non_null = (ManuallyDrop::new(self).1).0;
|
|
|
|
unsafe { Py::from_non_null(non_null) }
|
2023-12-26 13:16:41 +00:00
|
|
|
}
|
|
|
|
|
2024-03-20 12:52:09 +00:00
|
|
|
/// Removes the connection for this `Bound<T>` from the GIL, allowing
|
|
|
|
/// it to cross thread boundaries, without transferring ownership.
|
|
|
|
#[inline]
|
|
|
|
pub fn as_unbound(&self) -> &Py<T> {
|
|
|
|
&self.1
|
|
|
|
}
|
|
|
|
|
2023-12-24 14:34:08 +00:00
|
|
|
/// Casts this `Bound<T>` as the corresponding "GIL Ref" type.
|
|
|
|
///
|
|
|
|
/// This is a helper to be used for migration from the deprecated "GIL Refs" API.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2024-05-10 17:03:57 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2023-09-10 13:51:19 +00:00
|
|
|
pub fn as_gil_ref(&'py self) -> &'py T::AsRefTarget
|
|
|
|
where
|
2023-11-27 20:19:44 +00:00
|
|
|
T: HasPyGilRef,
|
2023-09-10 13:51:19 +00:00
|
|
|
{
|
2024-03-01 20:51:53 +00:00
|
|
|
#[allow(deprecated)]
|
|
|
|
unsafe {
|
|
|
|
self.py().from_borrowed_ptr(self.as_ptr())
|
|
|
|
}
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
|
2023-12-24 14:34:08 +00:00
|
|
|
/// Casts this `Bound<T>` as the corresponding "GIL Ref" type, registering the pointer on the
|
|
|
|
/// [release pool](Python::from_owned_ptr).
|
|
|
|
///
|
|
|
|
/// This is a helper to be used for migration from the deprecated "GIL Refs" API.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2024-05-10 17:03:57 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2023-09-10 13:51:19 +00:00
|
|
|
pub fn into_gil_ref(self) -> &'py T::AsRefTarget
|
|
|
|
where
|
2023-11-27 20:19:44 +00:00
|
|
|
T: HasPyGilRef,
|
2023-09-10 13:51:19 +00:00
|
|
|
{
|
2024-02-22 00:05:08 +00:00
|
|
|
#[allow(deprecated)]
|
|
|
|
unsafe {
|
|
|
|
self.py().from_owned_ptr(self.into_ptr())
|
|
|
|
}
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
unsafe impl<T> AsPyPointer for Bound<'_, T> {
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2023-09-10 13:51:19 +00:00
|
|
|
fn as_ptr(&self) -> *mut ffi::PyObject {
|
|
|
|
self.1.as_ptr()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
/// A borrowed equivalent to `Bound`.
|
2023-12-14 19:07:47 +00:00
|
|
|
///
|
2023-12-21 12:04:45 +00:00
|
|
|
/// The advantage of this over `&Bound` is that it avoids the need to have a pointer-to-pointer, as Bound
|
2023-12-14 19:07:47 +00:00
|
|
|
/// is already a pointer to an `ffi::PyObject``.
|
2023-12-20 15:42:43 +00:00
|
|
|
///
|
|
|
|
/// Similarly, this type is `Copy` and `Clone`, like a shared reference (`&T`).
|
2023-12-14 19:07:47 +00:00
|
|
|
#[repr(transparent)]
|
2023-12-21 12:20:33 +00:00
|
|
|
pub struct Borrowed<'a, 'py, T>(NonNull<ffi::PyObject>, PhantomData<&'a Py<T>>, Python<'py>);
|
2023-12-14 19:07:47 +00:00
|
|
|
|
2023-12-21 12:02:56 +00:00
|
|
|
impl<'py, T> Borrowed<'_, 'py, T> {
|
2024-03-17 09:17:09 +00:00
|
|
|
/// Creates a new owned [`Bound<T>`] from this borrowed reference by
|
|
|
|
/// increasing the reference count.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
/// ```
|
|
|
|
/// use pyo3::{prelude::*, types::PyTuple};
|
|
|
|
///
|
|
|
|
/// # fn main() -> PyResult<()> {
|
|
|
|
/// Python::with_gil(|py| -> PyResult<()> {
|
|
|
|
/// let tuple = PyTuple::new_bound(py, [1, 2, 3]);
|
2024-03-20 12:52:09 +00:00
|
|
|
///
|
2024-03-17 09:17:09 +00:00
|
|
|
/// // borrows from `tuple`, so can only be
|
|
|
|
/// // used while `tuple` stays alive
|
|
|
|
/// let borrowed = tuple.get_borrowed_item(0)?;
|
2024-03-20 12:52:09 +00:00
|
|
|
///
|
2024-03-17 09:17:09 +00:00
|
|
|
/// // creates a new owned reference, which
|
|
|
|
/// // can be used indendently of `tuple`
|
|
|
|
/// let bound = borrowed.to_owned();
|
|
|
|
/// drop(tuple);
|
|
|
|
///
|
|
|
|
/// assert_eq!(bound.extract::<i32>().unwrap(), 1);
|
|
|
|
/// Ok(())
|
|
|
|
/// })
|
|
|
|
/// # }
|
|
|
|
pub fn to_owned(self) -> Bound<'py, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
(*self).clone()
|
2023-12-21 08:58:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:02:56 +00:00
|
|
|
impl<'a, 'py> Borrowed<'a, 'py, PyAny> {
|
2024-02-18 22:03:43 +00:00
|
|
|
/// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Panics if `ptr` is null.
|
|
|
|
///
|
|
|
|
/// Prefer to use [`Bound::from_borrowed_ptr`], as that avoids the major safety risk
|
|
|
|
/// of needing to precisely define the lifetime `'a` for which the borrow is valid.
|
|
|
|
///
|
2023-12-14 19:07:47 +00:00
|
|
|
/// # Safety
|
2024-02-18 22:03:43 +00:00
|
|
|
///
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object
|
|
|
|
/// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
|
|
|
|
/// the caller and it is the caller's responsibility to ensure that the reference this is
|
|
|
|
/// derived from is valid for the lifetime `'a`.
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2024-02-18 22:03:43 +00:00
|
|
|
pub unsafe fn from_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
|
|
|
|
Self(
|
|
|
|
NonNull::new(ptr).unwrap_or_else(|| crate::err::panic_after_error(py)),
|
|
|
|
PhantomData,
|
|
|
|
py,
|
2023-12-14 19:07:47 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-02-18 22:03:43 +00:00
|
|
|
/// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Returns `None` if `ptr` is null.
|
|
|
|
///
|
|
|
|
/// Prefer to use [`Bound::from_borrowed_ptr_or_opt`], as that avoids the major safety risk
|
|
|
|
/// of needing to precisely define the lifetime `'a` for which the borrow is valid.
|
|
|
|
///
|
2023-12-14 19:07:47 +00:00
|
|
|
/// # Safety
|
2024-02-18 22:03:43 +00:00
|
|
|
///
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object, or null
|
|
|
|
/// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
|
|
|
|
/// the caller and it is the caller's responsibility to ensure that the reference this is
|
|
|
|
/// derived from is valid for the lifetime `'a`.
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-02-18 22:03:43 +00:00
|
|
|
pub unsafe fn from_ptr_or_opt(py: Python<'py>, ptr: *mut ffi::PyObject) -> Option<Self> {
|
2023-12-14 19:07:47 +00:00
|
|
|
NonNull::new(ptr).map(|ptr| Self(ptr, PhantomData, py))
|
|
|
|
}
|
|
|
|
|
2024-02-18 22:03:43 +00:00
|
|
|
/// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Returns an `Err` by calling `PyErr::fetch`
|
|
|
|
/// if `ptr` is null.
|
|
|
|
///
|
|
|
|
/// Prefer to use [`Bound::from_borrowed_ptr_or_err`], as that avoids the major safety risk
|
|
|
|
/// of needing to precisely define the lifetime `'a` for which the borrow is valid.
|
|
|
|
///
|
2023-12-14 19:07:47 +00:00
|
|
|
/// # Safety
|
2024-02-18 22:03:43 +00:00
|
|
|
///
|
|
|
|
/// - `ptr` must be a valid pointer to a Python object, or null
|
|
|
|
/// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
|
|
|
|
/// the caller and it is the caller's responsibility to ensure that the reference this is
|
|
|
|
/// derived from is valid for the lifetime `'a`.
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-02-18 22:03:43 +00:00
|
|
|
pub unsafe fn from_ptr_or_err(py: Python<'py>, ptr: *mut ffi::PyObject) -> PyResult<Self> {
|
|
|
|
NonNull::new(ptr).map_or_else(
|
|
|
|
|| Err(PyErr::fetch(py)),
|
|
|
|
|ptr| Ok(Self(ptr, PhantomData, py)),
|
2023-12-14 19:07:47 +00:00
|
|
|
)
|
|
|
|
}
|
2023-12-20 12:44:00 +00:00
|
|
|
|
|
|
|
/// # Safety
|
|
|
|
/// This is similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
|
|
|
|
/// the caller and it's the caller's responsibility to ensure that the reference this is
|
|
|
|
/// derived from is valid for the lifetime `'a`.
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2023-12-20 12:44:00 +00:00
|
|
|
pub(crate) unsafe fn from_ptr_unchecked(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
|
|
|
|
Self(NonNull::new_unchecked(ptr), PhantomData, py)
|
|
|
|
}
|
2024-01-30 20:55:22 +00:00
|
|
|
|
2024-03-15 07:53:52 +00:00
|
|
|
#[inline]
|
|
|
|
#[cfg(not(feature = "gil-refs"))]
|
|
|
|
pub(crate) fn downcast<T>(self) -> Result<Borrowed<'a, 'py, T>, DowncastError<'a, 'py>>
|
|
|
|
where
|
|
|
|
T: PyTypeCheck,
|
|
|
|
{
|
|
|
|
if T::type_check(&self) {
|
|
|
|
// Safety: type_check is responsible for ensuring that the type is correct
|
|
|
|
Ok(unsafe { self.downcast_unchecked() })
|
|
|
|
} else {
|
|
|
|
Err(DowncastError::new_from_borrowed(self, T::NAME))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-30 20:55:22 +00:00
|
|
|
/// Converts this `PyAny` to a concrete Python type without checking validity.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// Callers must ensure that the type is valid or risk type confusion.
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-01-30 20:55:22 +00:00
|
|
|
pub(crate) unsafe fn downcast_unchecked<T>(self) -> Borrowed<'a, 'py, T> {
|
|
|
|
Borrowed(self.0, PhantomData, self.2)
|
|
|
|
}
|
2023-12-14 19:07:47 +00:00
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<'a, 'py, T> From<&'a Bound<'py, T>> for Borrowed<'a, 'py, T> {
|
|
|
|
/// Create borrow on a Bound
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2023-12-21 12:04:45 +00:00
|
|
|
fn from(instance: &'a Bound<'py, T>) -> Self {
|
2023-12-24 13:48:13 +00:00
|
|
|
instance.as_borrowed()
|
2023-12-14 19:07:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-12 18:30:08 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2023-12-21 12:02:56 +00:00
|
|
|
impl<'py, T> Borrowed<'py, 'py, T>
|
2023-12-14 19:07:47 +00:00
|
|
|
where
|
|
|
|
T: HasPyGilRef,
|
|
|
|
{
|
2023-12-20 15:33:54 +00:00
|
|
|
pub(crate) fn into_gil_ref(self) -> &'py T::AsRefTarget {
|
|
|
|
// Safety: self is a borrow over `'py`.
|
2024-03-01 20:51:53 +00:00
|
|
|
#[allow(deprecated)]
|
|
|
|
unsafe {
|
|
|
|
self.py().from_borrowed_ptr(self.0.as_ptr())
|
|
|
|
}
|
2023-12-20 15:33:54 +00:00
|
|
|
}
|
2023-12-14 19:07:47 +00:00
|
|
|
}
|
|
|
|
|
2023-12-21 12:02:56 +00:00
|
|
|
impl<T> std::fmt::Debug for Borrowed<'_, '_, T> {
|
2023-12-14 19:07:47 +00:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2023-12-21 12:04:45 +00:00
|
|
|
Bound::fmt(self, f)
|
2023-12-14 19:07:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:02:56 +00:00
|
|
|
impl<'py, T> Deref for Borrowed<'_, 'py, T> {
|
2023-12-21 12:04:45 +00:00
|
|
|
type Target = Bound<'py, T>;
|
2023-12-14 19:07:47 +00:00
|
|
|
|
|
|
|
#[inline]
|
2023-12-21 12:04:45 +00:00
|
|
|
fn deref(&self) -> &Bound<'py, T> {
|
|
|
|
// safety: Bound has the same layout as NonNull<ffi::PyObject>
|
|
|
|
unsafe { &*(&self.0 as *const _ as *const Bound<'py, T>) }
|
2023-12-14 19:07:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:02:56 +00:00
|
|
|
impl<T> Clone for Borrowed<'_, '_, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-20 15:42:43 +00:00
|
|
|
fn clone(&self) -> Self {
|
|
|
|
*self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:02:56 +00:00
|
|
|
impl<T> Copy for Borrowed<'_, '_, T> {}
|
2023-12-20 15:42:43 +00:00
|
|
|
|
2024-01-23 08:43:40 +00:00
|
|
|
impl<T> ToPyObject for Borrowed<'_, '_, T> {
|
|
|
|
/// Converts `Py` instance -> PyObject.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2024-01-23 08:43:40 +00:00
|
|
|
fn to_object(&self, py: Python<'_>) -> PyObject {
|
|
|
|
(*self).into_py(py)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> IntoPy<PyObject> for Borrowed<'_, '_, T> {
|
|
|
|
/// Converts `Py` instance -> PyObject.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2024-01-23 08:43:40 +00:00
|
|
|
fn into_py(self, py: Python<'_>) -> PyObject {
|
|
|
|
self.to_owned().into_py(py)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-03 01:31:05 +00:00
|
|
|
/// A GIL-independent reference to an object allocated on the Python heap.
|
2019-02-13 20:35:26 +00:00
|
|
|
///
|
2021-07-03 01:31:05 +00:00
|
|
|
/// This type does not auto-dereference to the inner object because you must prove you hold the GIL to access it.
|
|
|
|
/// Instead, call one of its methods to access the inner object:
|
2024-05-01 10:57:03 +00:00
|
|
|
/// - [`Py::bind`] or [`Py::into_bound`], to borrow a GIL-bound reference to the contained object.
|
2021-07-03 01:31:05 +00:00
|
|
|
/// - [`Py::borrow`], [`Py::try_borrow`], [`Py::borrow_mut`], or [`Py::try_borrow_mut`],
|
|
|
|
/// to get a (mutable) reference to a contained pyclass, using a scheme similar to std's [`RefCell`].
|
2024-05-01 10:57:03 +00:00
|
|
|
/// See the [guide entry](https://pyo3.rs/latest/class.html#bound-and-interior-mutability)
|
2021-07-03 01:31:05 +00:00
|
|
|
/// for more information.
|
2024-05-01 10:57:03 +00:00
|
|
|
/// - You can call methods directly on `Py` with [`Py::call_bound`], [`Py::call_method_bound`] and friends.
|
2021-07-03 01:31:05 +00:00
|
|
|
/// These require passing in the [`Python<'py>`](crate::Python) token but are otherwise similar to the corresponding
|
|
|
|
/// methods on [`PyAny`].
|
2020-03-17 09:04:03 +00:00
|
|
|
///
|
2024-02-20 07:08:49 +00:00
|
|
|
/// # Example: Storing Python objects in `#[pyclass]` structs
|
|
|
|
///
|
|
|
|
/// Usually `Bound<'py, T>` is recommended for interacting with Python objects as its lifetime `'py`
|
|
|
|
/// is an association to the GIL and that enables many operations to be done as efficiently as possible.
|
|
|
|
///
|
|
|
|
/// However, `#[pyclass]` structs cannot carry a lifetime, so `Py<T>` is the only way to store
|
|
|
|
/// a Python object in a `#[pyclass]` struct.
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
2021-07-03 16:01:12 +00:00
|
|
|
/// For example, this won't compile:
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// ```compile_fail
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
/// # use pyo3::types::PyDict;
|
|
|
|
/// #
|
2021-07-03 16:01:12 +00:00
|
|
|
/// #[pyclass]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// struct Foo<'py> {
|
2024-02-20 07:08:49 +00:00
|
|
|
/// inner: Bound<'py, PyDict>,
|
2021-07-03 01:31:05 +00:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// impl Foo {
|
|
|
|
/// fn new() -> Foo {
|
|
|
|
/// let foo = Python::with_gil(|py| {
|
|
|
|
/// // `py` will only last for this scope.
|
|
|
|
///
|
2024-02-20 07:08:49 +00:00
|
|
|
/// // `Bound<'py, PyDict>` inherits the GIL lifetime from `py` and
|
2021-07-24 07:47:02 +00:00
|
|
|
/// // so won't be able to outlive this closure.
|
2024-02-20 07:08:49 +00:00
|
|
|
/// let dict: Bound<'_, PyDict> = PyDict::new_bound(py);
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// // because `Foo` contains `dict` its lifetime
|
|
|
|
/// // is now also tied to `py`.
|
|
|
|
/// Foo { inner: dict }
|
|
|
|
/// });
|
|
|
|
/// // Foo is no longer valid.
|
|
|
|
/// // Returning it from this function is a 💥 compiler error 💥
|
|
|
|
/// foo
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// [`Py`]`<T>` can be used to get around this by converting `dict` into a GIL-independent reference:
|
|
|
|
///
|
|
|
|
/// ```rust
|
2021-10-14 21:15:25 +00:00
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
/// use pyo3::types::PyDict;
|
|
|
|
///
|
2021-07-03 16:01:12 +00:00
|
|
|
/// #[pyclass]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// struct Foo {
|
|
|
|
/// inner: Py<PyDict>,
|
|
|
|
/// }
|
|
|
|
///
|
2021-10-14 21:15:25 +00:00
|
|
|
/// #[pymethods]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// impl Foo {
|
2021-10-14 21:15:25 +00:00
|
|
|
/// #[new]
|
|
|
|
/// fn __new__() -> Foo {
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Python::with_gil(|py| {
|
2024-02-11 23:55:56 +00:00
|
|
|
/// let dict: Py<PyDict> = PyDict::new_bound(py).unbind();
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Foo { inner: dict }
|
|
|
|
/// })
|
|
|
|
/// }
|
|
|
|
/// }
|
2021-10-14 21:15:25 +00:00
|
|
|
/// #
|
|
|
|
/// # fn main() -> PyResult<()> {
|
|
|
|
/// # Python::with_gil(|py| {
|
2024-02-22 09:35:47 +00:00
|
|
|
/// # let m = pyo3::types::PyModule::new_bound(py, "test")?;
|
2021-10-14 21:15:25 +00:00
|
|
|
/// # m.add_class::<Foo>()?;
|
|
|
|
/// #
|
2024-02-22 09:35:47 +00:00
|
|
|
/// # let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?;
|
2021-10-14 21:15:25 +00:00
|
|
|
/// # let dict = &foo.borrow().inner;
|
2024-02-22 09:35:47 +00:00
|
|
|
/// # let dict: &Bound<'_, PyDict> = dict.bind(py);
|
2021-10-14 21:15:25 +00:00
|
|
|
/// #
|
|
|
|
/// # Ok(())
|
|
|
|
/// # })
|
|
|
|
/// # }
|
2021-07-03 01:31:05 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// This can also be done with other pyclasses:
|
|
|
|
/// ```rust
|
2021-10-14 21:15:25 +00:00
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
///
|
2021-07-03 01:31:05 +00:00
|
|
|
/// #[pyclass]
|
2021-10-14 21:15:25 +00:00
|
|
|
/// struct Bar {/* ... */}
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
2021-07-03 16:01:12 +00:00
|
|
|
/// #[pyclass]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// struct Foo {
|
|
|
|
/// inner: Py<Bar>,
|
|
|
|
/// }
|
|
|
|
///
|
2021-10-14 21:15:25 +00:00
|
|
|
/// #[pymethods]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// impl Foo {
|
2021-10-14 21:15:25 +00:00
|
|
|
/// #[new]
|
|
|
|
/// fn __new__() -> PyResult<Foo> {
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Python::with_gil(|py| {
|
|
|
|
/// let bar: Py<Bar> = Py::new(py, Bar {})?;
|
|
|
|
/// Ok(Foo { inner: bar })
|
|
|
|
/// })
|
|
|
|
/// }
|
|
|
|
/// }
|
2021-10-14 21:15:25 +00:00
|
|
|
/// #
|
|
|
|
/// # fn main() -> PyResult<()> {
|
|
|
|
/// # Python::with_gil(|py| {
|
2024-02-22 09:35:47 +00:00
|
|
|
/// # let m = pyo3::types::PyModule::new_bound(py, "test")?;
|
2021-10-14 21:15:25 +00:00
|
|
|
/// # m.add_class::<Foo>()?;
|
|
|
|
/// #
|
2024-02-22 09:35:47 +00:00
|
|
|
/// # let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?;
|
2021-10-14 21:15:25 +00:00
|
|
|
/// # let bar = &foo.borrow().inner;
|
|
|
|
/// # let bar: &Bar = &*bar.borrow(py);
|
|
|
|
/// #
|
|
|
|
/// # Ok(())
|
|
|
|
/// # })
|
|
|
|
/// # }
|
2021-07-03 01:31:05 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Example: Shared ownership of Python objects
|
|
|
|
///
|
|
|
|
/// `Py<T>` can be used to share ownership of a Python object, similar to std's [`Rc`]`<T>`.
|
|
|
|
/// As with [`Rc`]`<T>`, cloning it increases its reference count rather than duplicating
|
|
|
|
/// the underlying object.
|
|
|
|
///
|
|
|
|
/// This can be done using either [`Py::clone_ref`] or [`Py`]`<T>`'s [`Clone`] trait implementation.
|
|
|
|
/// [`Py::clone_ref`] will be faster if you happen to be already holding the GIL.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
/// use pyo3::types::PyDict;
|
|
|
|
///
|
|
|
|
/// # fn main() {
|
|
|
|
/// Python::with_gil(|py| {
|
2024-02-11 23:55:56 +00:00
|
|
|
/// let first: Py<PyDict> = PyDict::new_bound(py).unbind();
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// // All of these are valid syntax
|
|
|
|
/// let second = Py::clone_ref(&first, py);
|
|
|
|
/// let third = first.clone_ref(py);
|
2024-05-11 14:48:45 +00:00
|
|
|
/// #[cfg(feature = "py-clone")]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// let fourth = Py::clone(&first);
|
2024-05-11 14:48:45 +00:00
|
|
|
/// #[cfg(feature = "py-clone")]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// let fifth = first.clone();
|
|
|
|
///
|
|
|
|
/// // Disposing of our original `Py<PyDict>` just decrements the reference count.
|
|
|
|
/// drop(first);
|
|
|
|
///
|
|
|
|
/// // They all point to the same object
|
2022-03-30 10:56:14 +00:00
|
|
|
/// assert!(second.is(&third));
|
2024-05-11 14:48:45 +00:00
|
|
|
/// #[cfg(feature = "py-clone")]
|
2022-03-30 10:56:14 +00:00
|
|
|
/// assert!(fourth.is(&fifth));
|
2024-05-11 14:48:45 +00:00
|
|
|
/// #[cfg(feature = "py-clone")]
|
2022-03-30 10:56:14 +00:00
|
|
|
/// assert!(second.is(&fourth));
|
2021-07-03 01:31:05 +00:00
|
|
|
/// });
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Preventing reference cycles
|
|
|
|
///
|
|
|
|
/// It is easy to accidentally create reference cycles using [`Py`]`<T>`.
|
|
|
|
/// The Python interpreter can break these reference cycles within pyclasses if they
|
2022-03-30 10:56:14 +00:00
|
|
|
/// [integrate with the garbage collector][gc]. If your pyclass contains other Python
|
|
|
|
/// objects you should implement it to avoid leaking memory.
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
2021-08-21 08:23:10 +00:00
|
|
|
/// # A note on Python reference counts
|
|
|
|
///
|
|
|
|
/// Dropping a [`Py`]`<T>` will eventually decrease Python's reference count
|
|
|
|
/// of the pointed-to variable, allowing Python's garbage collector to free
|
|
|
|
/// the associated memory, but this may not happen immediately. This is
|
|
|
|
/// because a [`Py`]`<T>` can be dropped at any time, but the Python reference
|
|
|
|
/// count can only be modified when the GIL is held.
|
|
|
|
///
|
|
|
|
/// If a [`Py`]`<T>` is dropped while its thread happens to be holding the
|
|
|
|
/// GIL then the Python reference count will be decreased immediately.
|
|
|
|
/// Otherwise, the reference count will be decreased the next time the GIL is
|
|
|
|
/// reacquired.
|
|
|
|
///
|
2024-02-21 22:56:03 +00:00
|
|
|
/// If you happen to be already holding the GIL, [`Py::drop_ref`] will decrease
|
|
|
|
/// the Python reference count immediately and will execute slightly faster than
|
|
|
|
/// relying on implicit [`Drop`]s.
|
|
|
|
///
|
2021-07-03 01:31:05 +00:00
|
|
|
/// # A note on `Send` and `Sync`
|
|
|
|
///
|
|
|
|
/// Accessing this object is threadsafe, since any access to its API requires a [`Python<'py>`](crate::Python) token.
|
2024-02-17 17:04:35 +00:00
|
|
|
/// As you can only get this by acquiring the GIL, `Py<...>` implements [`Send`] and [`Sync`].
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// [`Rc`]: std::rc::Rc
|
|
|
|
/// [`RefCell`]: std::cell::RefCell
|
2022-03-30 10:56:14 +00:00
|
|
|
/// [gc]: https://pyo3.rs/main/class/protocols.html#garbage-collector-integration
|
2018-11-12 20:36:08 +00:00
|
|
|
#[repr(transparent)]
|
2019-10-27 09:03:01 +00:00
|
|
|
pub struct Py<T>(NonNull<ffi::PyObject>, PhantomData<T>);
|
2017-06-20 03:55:07 +00:00
|
|
|
|
2022-02-08 15:56:19 +00:00
|
|
|
// The inner value is only accessed through ways that require proving the gil is held
|
|
|
|
#[cfg(feature = "nightly")]
|
|
|
|
unsafe impl<T> crate::marker::Ungil for Py<T> {}
|
2020-06-08 00:50:55 +00:00
|
|
|
unsafe impl<T> Send for Py<T> {}
|
|
|
|
unsafe impl<T> Sync for Py<T> {}
|
2017-06-20 03:55:07 +00:00
|
|
|
|
2020-06-14 21:36:07 +00:00
|
|
|
impl<T> Py<T>
|
|
|
|
where
|
|
|
|
T: PyClass,
|
|
|
|
{
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Creates a new instance `Py<T>` of a `#[pyclass]` on the Python heap.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
///
|
|
|
|
/// #[pyclass]
|
|
|
|
/// struct Foo {/* fields omitted */}
|
|
|
|
///
|
|
|
|
/// # fn main() -> PyResult<()> {
|
2024-05-11 14:48:45 +00:00
|
|
|
/// let foo = Python::with_gil(|py| -> PyResult<_> {
|
2021-07-03 01:31:05 +00:00
|
|
|
/// let foo: Py<Foo> = Py::new(py, Foo {})?;
|
|
|
|
/// Ok(foo)
|
|
|
|
/// })?;
|
2024-05-11 14:48:45 +00:00
|
|
|
/// # Python::with_gil(move |_py| drop(foo));
|
2021-07-03 01:31:05 +00:00
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn new(py: Python<'_>, value: impl Into<PyClassInitializer<T>>) -> PyResult<Py<T>> {
|
2024-03-03 07:00:59 +00:00
|
|
|
Bound::new(py, value).map(Bound::unbind)
|
2019-02-13 20:35:26 +00:00
|
|
|
}
|
2020-08-09 21:47:54 +00:00
|
|
|
}
|
2019-02-13 20:35:26 +00:00
|
|
|
|
2024-05-12 18:30:08 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2020-08-09 21:47:54 +00:00
|
|
|
impl<T> Py<T>
|
|
|
|
where
|
2023-11-27 20:19:44 +00:00
|
|
|
T: HasPyGilRef,
|
2020-08-09 21:47:54 +00:00
|
|
|
{
|
2021-07-03 16:01:12 +00:00
|
|
|
/// Borrows a GIL-bound reference to the contained `T`.
|
|
|
|
///
|
|
|
|
/// By binding to the GIL lifetime, this allows the GIL-bound reference to not require
|
|
|
|
/// [`Python<'py>`](crate::Python) for any of its methods, which makes calling methods
|
|
|
|
/// on it more ergonomic.
|
2020-08-09 21:47:54 +00:00
|
|
|
///
|
|
|
|
/// For native types, this reference is `&T`. For pyclasses, this is `&PyCell<T>`.
|
|
|
|
///
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Note that the lifetime of the returned reference is the shortest of `&self` and
|
|
|
|
/// [`Python<'py>`](crate::Python).
|
|
|
|
/// Consider using [`Py::into_ref`] instead if this poses a problem.
|
|
|
|
///
|
2020-08-09 21:47:54 +00:00
|
|
|
/// # Examples
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
2020-08-09 21:47:54 +00:00
|
|
|
/// Get access to `&PyList` from `Py<PyList>`:
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
/// # use pyo3::types::PyList;
|
2021-07-03 01:31:05 +00:00
|
|
|
/// #
|
|
|
|
/// Python::with_gil(|py| {
|
2024-01-23 09:23:30 +00:00
|
|
|
/// let list: Py<PyList> = PyList::empty_bound(py).into();
|
2024-02-29 07:15:34 +00:00
|
|
|
/// # #[allow(deprecated)]
|
2024-01-23 09:23:30 +00:00
|
|
|
/// let list: &PyList = list.as_ref(py);
|
|
|
|
/// assert_eq!(list.len(), 0);
|
2021-07-03 01:31:05 +00:00
|
|
|
/// });
|
2020-08-09 21:47:54 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Get access to `&PyCell<MyClass>` from `Py<MyClass>`:
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use pyo3::prelude::*;
|
2021-07-03 01:31:05 +00:00
|
|
|
/// #
|
2020-08-09 21:47:54 +00:00
|
|
|
/// #[pyclass]
|
2021-10-14 21:15:25 +00:00
|
|
|
/// struct MyClass {}
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// Python::with_gil(|py| {
|
2021-10-14 21:15:25 +00:00
|
|
|
/// let my_class: Py<MyClass> = Py::new(py, MyClass {}).unwrap();
|
2024-02-29 07:15:34 +00:00
|
|
|
/// # #[allow(deprecated)]
|
2021-07-03 01:31:05 +00:00
|
|
|
/// let my_class_cell: &PyCell<MyClass> = my_class.as_ref(py);
|
|
|
|
/// assert!(my_class_cell.try_borrow().is_ok());
|
|
|
|
/// });
|
2020-08-09 21:47:54 +00:00
|
|
|
/// ```
|
2024-05-01 10:57:03 +00:00
|
|
|
#[deprecated(
|
|
|
|
since = "0.21.0",
|
|
|
|
note = "use `obj.bind(py)` instead of `obj.as_ref(py)`"
|
2024-02-29 07:15:34 +00:00
|
|
|
)]
|
2020-08-09 21:47:54 +00:00
|
|
|
pub fn as_ref<'py>(&'py self, _py: Python<'py>) -> &'py T::AsRefTarget {
|
|
|
|
let any = self.as_ptr() as *const PyAny;
|
|
|
|
unsafe { PyNativeType::unchecked_downcast(&*any) }
|
|
|
|
}
|
2020-08-09 21:56:30 +00:00
|
|
|
|
2021-07-03 16:01:12 +00:00
|
|
|
/// Borrows a GIL-bound reference to the contained `T` independently of the lifetime of `T`.
|
|
|
|
///
|
|
|
|
/// This method is similar to [`as_ref`](#method.as_ref) but consumes `self` and registers the
|
2020-08-09 21:56:30 +00:00
|
|
|
/// Python object reference in PyO3's object storage. The reference count for the Python
|
|
|
|
/// object will not be decreased until the GIL lifetime ends.
|
|
|
|
///
|
2021-07-03 16:01:12 +00:00
|
|
|
/// You should prefer using [`as_ref`](#method.as_ref) if you can as it'll have less overhead.
|
|
|
|
///
|
2021-03-20 07:45:56 +00:00
|
|
|
/// # Examples
|
2020-08-09 21:56:30 +00:00
|
|
|
///
|
2021-07-03 16:01:12 +00:00
|
|
|
/// [`Py::as_ref`]'s lifetime limitation forbids creating a function that references a
|
|
|
|
/// variable created inside the function.
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// ```rust,compile_fail
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
/// #
|
|
|
|
/// fn new_py_any<'py>(py: Python<'py>, value: impl IntoPy<Py<PyAny>>) -> &'py PyAny {
|
|
|
|
/// let obj: Py<PyAny> = value.into_py(py);
|
|
|
|
///
|
|
|
|
/// // The lifetime of the return value of this function is the shortest
|
|
|
|
/// // of `obj` and `py`. As `obj` is owned by the current function,
|
|
|
|
/// // Rust won't let the return value escape this function!
|
|
|
|
/// obj.as_ref(py)
|
|
|
|
/// }
|
2020-08-09 21:56:30 +00:00
|
|
|
/// ```
|
2021-07-03 16:01:12 +00:00
|
|
|
///
|
2021-07-03 10:11:13 +00:00
|
|
|
/// This can be solved by using [`Py::into_ref`] instead, which does not suffer from this issue.
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Note that the lifetime of the [`Python<'py>`](crate::Python) token is transferred to
|
|
|
|
/// the returned reference.
|
|
|
|
///
|
|
|
|
/// ```rust
|
2020-08-09 21:56:30 +00:00
|
|
|
/// # use pyo3::prelude::*;
|
2021-10-14 21:15:25 +00:00
|
|
|
/// # #[allow(dead_code)] // This is just to show it compiles.
|
2021-07-03 01:31:05 +00:00
|
|
|
/// fn new_py_any<'py>(py: Python<'py>, value: impl IntoPy<Py<PyAny>>) -> &'py PyAny {
|
|
|
|
/// let obj: Py<PyAny> = value.into_py(py);
|
2020-08-10 19:08:48 +00:00
|
|
|
///
|
2021-07-03 01:31:05 +00:00
|
|
|
/// // This reference's lifetime is determined by `py`'s lifetime.
|
|
|
|
/// // Because that originates from outside this function,
|
|
|
|
/// // this return value is allowed.
|
2024-02-20 07:10:45 +00:00
|
|
|
/// # #[allow(deprecated)]
|
2020-08-10 19:08:48 +00:00
|
|
|
/// obj.into_ref(py)
|
|
|
|
/// }
|
2020-08-09 21:56:30 +00:00
|
|
|
/// ```
|
2024-05-01 10:57:03 +00:00
|
|
|
#[deprecated(
|
|
|
|
since = "0.21.0",
|
|
|
|
note = "use `obj.into_bound(py)` instead of `obj.into_ref(py)`"
|
2024-02-20 07:10:45 +00:00
|
|
|
)]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn into_ref(self, py: Python<'_>) -> &T::AsRefTarget {
|
2024-02-22 00:05:08 +00:00
|
|
|
#[allow(deprecated)]
|
|
|
|
unsafe {
|
|
|
|
py.from_owned_ptr(self.into_ptr())
|
|
|
|
}
|
2020-08-09 21:56:30 +00:00
|
|
|
}
|
2020-08-09 21:47:54 +00:00
|
|
|
}
|
|
|
|
|
2023-07-30 20:58:21 +00:00
|
|
|
impl<T> Py<T> {
|
|
|
|
/// 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.
|
|
|
|
#[inline]
|
|
|
|
pub fn as_ptr(&self) -> *mut ffi::PyObject {
|
|
|
|
self.0.as_ptr()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns an owned raw FFI pointer represented by self.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// The reference is owned; when finished the caller should either transfer ownership
|
|
|
|
/// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)).
|
|
|
|
#[inline]
|
|
|
|
pub fn into_ptr(self) -> *mut ffi::PyObject {
|
2024-02-01 09:27:44 +00:00
|
|
|
ManuallyDrop::new(self).0.as_ptr()
|
2023-07-30 20:58:21 +00:00
|
|
|
}
|
2024-02-01 09:07:36 +00:00
|
|
|
|
|
|
|
/// Helper to cast to `Py<PyAny>`.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2024-02-01 09:07:36 +00:00
|
|
|
pub fn as_any(&self) -> &Py<PyAny> {
|
|
|
|
// Safety: all Py<T> have the same memory layout, and all Py<T> are valid
|
|
|
|
// Py<PyAny>, so pointer casting is valid.
|
|
|
|
unsafe { &*(self as *const Self).cast::<Py<PyAny>>() }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Helper to cast to `Py<PyAny>`, transferring ownership.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2024-02-01 09:07:36 +00:00
|
|
|
pub fn into_any(self) -> Py<PyAny> {
|
|
|
|
// Safety: all Py<T> are valid Py<PyAny>
|
2024-02-01 09:27:44 +00:00
|
|
|
unsafe { Py::from_non_null(ManuallyDrop::new(self).0) }
|
2024-02-01 09:07:36 +00:00
|
|
|
}
|
2023-07-30 20:58:21 +00:00
|
|
|
}
|
|
|
|
|
2020-08-09 21:47:54 +00:00
|
|
|
impl<T> Py<T>
|
|
|
|
where
|
|
|
|
T: PyClass,
|
|
|
|
{
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Immutably borrows the value `T`.
|
|
|
|
///
|
|
|
|
/// This borrow lasts while the returned [`PyRef`] exists.
|
|
|
|
/// Multiple immutable borrows can be taken out at the same time.
|
2020-06-14 21:36:07 +00:00
|
|
|
///
|
2023-05-16 19:48:59 +00:00
|
|
|
/// For frozen classes, the simpler [`get`][Self::get] is available.
|
|
|
|
///
|
2024-05-12 18:30:08 +00:00
|
|
|
/// Equivalent to `self.bind(py).borrow()` - see [`Bound::borrow`].
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
/// #
|
|
|
|
/// #[pyclass]
|
|
|
|
/// struct Foo {
|
|
|
|
/// inner: u8,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// # fn main() -> PyResult<()> {
|
|
|
|
/// 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(())
|
|
|
|
/// })?;
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2020-06-14 21:36:07 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
2020-06-14 21:36:07 +00:00
|
|
|
/// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
|
|
|
|
/// [`try_borrow`](#method.try_borrow).
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2020-06-14 21:36:07 +00:00
|
|
|
pub fn borrow<'py>(&'py self, py: Python<'py>) -> PyRef<'py, T> {
|
2024-02-18 00:09:56 +00:00
|
|
|
self.bind(py).borrow()
|
2020-06-14 21:36:07 +00:00
|
|
|
}
|
|
|
|
|
2021-07-03 01:31:05 +00:00
|
|
|
/// Mutably borrows the value `T`.
|
|
|
|
///
|
|
|
|
/// This borrow lasts while the returned [`PyRefMut`] exists.
|
2020-06-14 21:36:07 +00:00
|
|
|
///
|
2024-05-12 18:30:08 +00:00
|
|
|
/// Equivalent to `self.bind(py).borrow_mut()` - see [`Bound::borrow_mut`].
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
/// #
|
|
|
|
/// #[pyclass]
|
|
|
|
/// struct Foo {
|
|
|
|
/// inner: u8,
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// # fn main() -> PyResult<()> {
|
|
|
|
/// 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(())
|
|
|
|
/// })?;
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2020-06-14 21:36:07 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
2023-02-19 20:12:06 +00:00
|
|
|
/// Panics if the value is currently borrowed. For a non-panicking variant, use
|
2020-06-14 21:36:07 +00:00
|
|
|
/// [`try_borrow_mut`](#method.try_borrow_mut).
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2021-11-22 08:26:34 +00:00
|
|
|
pub fn borrow_mut<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T>
|
|
|
|
where
|
2022-06-11 11:20:43 +00:00
|
|
|
T: PyClass<Frozen = False>,
|
2021-11-22 08:26:34 +00:00
|
|
|
{
|
2024-02-18 00:09:56 +00:00
|
|
|
self.bind(py).borrow_mut()
|
2020-06-14 21:36:07 +00:00
|
|
|
}
|
|
|
|
|
2021-07-03 01:31:05 +00:00
|
|
|
/// 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.
|
2020-06-14 21:36:07 +00:00
|
|
|
///
|
|
|
|
/// This is the non-panicking variant of [`borrow`](#method.borrow).
|
|
|
|
///
|
2023-05-16 19:48:59 +00:00
|
|
|
/// For frozen classes, the simpler [`get`][Self::get] is available.
|
|
|
|
///
|
2024-05-12 18:30:08 +00:00
|
|
|
/// Equivalent to `self.bind(py).try_borrow()` - see [`Bound::try_borrow`].
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2020-06-14 21:36:07 +00:00
|
|
|
pub fn try_borrow<'py>(&'py self, py: Python<'py>) -> Result<PyRef<'py, T>, PyBorrowError> {
|
2024-02-18 00:09:56 +00:00
|
|
|
self.bind(py).try_borrow()
|
2020-06-14 21:36:07 +00:00
|
|
|
}
|
|
|
|
|
2021-07-03 10:11:41 +00:00
|
|
|
/// Attempts to mutably borrow the value `T`, returning an error if the value is currently borrowed.
|
2021-07-03 01:31:05 +00:00
|
|
|
///
|
|
|
|
/// The borrow lasts while the returned [`PyRefMut`] exists.
|
2020-06-14 21:36:07 +00:00
|
|
|
///
|
|
|
|
/// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
|
|
|
|
///
|
2024-05-12 18:30:08 +00:00
|
|
|
/// Equivalent to `self.bind(py).try_borrow_mut()` - see [`Bound::try_borrow_mut`].
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2020-06-14 21:36:07 +00:00
|
|
|
pub fn try_borrow_mut<'py>(
|
|
|
|
&'py self,
|
|
|
|
py: Python<'py>,
|
2021-11-22 08:26:34 +00:00
|
|
|
) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
|
|
|
|
where
|
2022-06-11 11:20:43 +00:00
|
|
|
T: PyClass<Frozen = False>,
|
2021-11-22 08:26:34 +00:00
|
|
|
{
|
2024-02-18 00:09:56 +00:00
|
|
|
self.bind(py).try_borrow_mut()
|
2020-06-14 21:36:07 +00:00
|
|
|
}
|
2023-05-16 19:48:59 +00:00
|
|
|
|
|
|
|
/// 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};
|
|
|
|
/// # use pyo3::prelude::*;
|
|
|
|
///
|
|
|
|
/// #[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);
|
2024-05-11 14:48:45 +00:00
|
|
|
/// # Python::with_gil(move |_py| drop(cell));
|
2023-05-16 19:48:59 +00:00
|
|
|
/// ```
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2023-05-16 19:48:59 +00:00
|
|
|
pub fn get(&self) -> &T
|
|
|
|
where
|
|
|
|
T: PyClass<Frozen = True> + Sync,
|
|
|
|
{
|
2024-03-03 07:00:59 +00:00
|
|
|
// Safety: The class itself is frozen and `Sync`
|
|
|
|
unsafe { &*self.get_class_object().get_ptr() }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get a view on the underlying `PyClass` contents.
|
2024-03-30 22:10:21 +00:00
|
|
|
#[inline]
|
2024-03-03 07:00:59 +00:00
|
|
|
pub(crate) fn get_class_object(&self) -> &PyClassObject<T> {
|
|
|
|
let class_object = self.as_ptr().cast::<PyClassObject<T>>();
|
|
|
|
// Safety: Bound<T: PyClass> is known to contain an object which is laid out in memory as a
|
|
|
|
// PyClassObject<T>.
|
|
|
|
unsafe { &*class_object }
|
2023-05-16 19:48:59 +00:00
|
|
|
}
|
2020-06-14 21:36:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Py<T> {
|
2023-09-10 13:51:19 +00:00
|
|
|
/// Attaches this `Py` to the given Python context, allowing access to further Python APIs.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-21 13:00:14 +00:00
|
|
|
pub fn bind<'py>(&self, _py: Python<'py>) -> &Bound<'py, T> {
|
2023-12-21 12:04:45 +00:00
|
|
|
// Safety: `Bound` has the same layout as `Py`
|
2023-09-10 13:51:19 +00:00
|
|
|
unsafe { &*(self as *const Py<T>).cast() }
|
|
|
|
}
|
|
|
|
|
2023-12-21 13:00:14 +00:00
|
|
|
/// Same as `bind` but takes ownership of `self`.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-21 13:00:14 +00:00
|
|
|
pub fn into_bound(self, py: Python<'_>) -> Bound<'_, T> {
|
2023-12-21 12:04:45 +00:00
|
|
|
Bound(py, ManuallyDrop::new(self))
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
|
2023-12-21 13:00:14 +00:00
|
|
|
/// Same as `bind` but produces a `Borrowed<T>` instead of a `Bound<T>`.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2023-12-21 13:00:14 +00:00
|
|
|
pub fn bind_borrowed<'a, 'py>(&'a self, py: Python<'py>) -> Borrowed<'a, 'py, T> {
|
2023-12-21 12:02:56 +00:00
|
|
|
Borrowed(self.0, PhantomData, py)
|
2023-12-14 19:07:47 +00:00
|
|
|
}
|
|
|
|
|
2022-02-25 19:39:45 +00:00
|
|
|
/// Returns whether `self` and `other` point to the same object. To compare
|
2024-05-09 22:21:48 +00:00
|
|
|
/// the equality of two objects (the `==` operator), use [`eq`](PyAnyMethods::eq).
|
2022-02-25 19:39:45 +00:00
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self is other`.
|
|
|
|
#[inline]
|
|
|
|
pub fn is<U: AsPyPointer>(&self, o: &U) -> bool {
|
|
|
|
self.as_ptr() == o.as_ptr()
|
|
|
|
}
|
|
|
|
|
2020-03-17 14:16:15 +00:00
|
|
|
/// Gets the reference count of the `ffi::PyObject` pointer.
|
2017-06-20 03:55:07 +00:00
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn get_refcnt(&self, _py: Python<'_>) -> isize {
|
2018-11-08 15:09:52 +00:00
|
|
|
unsafe { ffi::Py_REFCNT(self.0.as_ptr()) }
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
|
|
|
|
2021-07-03 01:31:05 +00:00
|
|
|
/// 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
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
/// use pyo3::types::PyDict;
|
|
|
|
///
|
|
|
|
/// # fn main() {
|
|
|
|
/// Python::with_gil(|py| {
|
2024-02-11 23:55:56 +00:00
|
|
|
/// let first: Py<PyDict> = PyDict::new_bound(py).unbind();
|
2021-07-03 01:31:05 +00:00
|
|
|
/// let second = Py::clone_ref(&first, py);
|
|
|
|
///
|
|
|
|
/// // Both point to the same object
|
2022-03-30 10:56:14 +00:00
|
|
|
/// assert!(first.is(&second));
|
2021-07-03 01:31:05 +00:00
|
|
|
/// });
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2017-06-20 03:55:07 +00:00
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn clone_ref(&self, py: Python<'_>) -> Py<T> {
|
2020-06-10 07:46:39 +00:00
|
|
|
unsafe { Py::from_borrowed_ptr(py, self.0.as_ptr()) }
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
2018-11-12 20:36:08 +00:00
|
|
|
|
2024-02-21 22:56:03 +00:00
|
|
|
/// 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
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
/// use pyo3::types::PyDict;
|
|
|
|
///
|
|
|
|
/// # fn main() {
|
|
|
|
/// Python::with_gil(|py| {
|
|
|
|
/// let object: Py<PyDict> = PyDict::new_bound(py).unbind();
|
|
|
|
///
|
|
|
|
/// // some usage of object
|
|
|
|
///
|
|
|
|
/// object.drop_ref(py);
|
|
|
|
/// });
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn drop_ref(self, py: Python<'_>) {
|
|
|
|
let _ = self.into_bound(py);
|
|
|
|
}
|
|
|
|
|
2020-07-21 23:40:31 +00:00
|
|
|
/// Returns whether the object is considered to be None.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self is None`.
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn is_none(&self, _py: Python<'_>) -> bool {
|
2020-07-21 23:40:31 +00:00
|
|
|
unsafe { ffi::Py_None() == self.as_ptr() }
|
|
|
|
}
|
|
|
|
|
2023-01-25 11:05:14 +00:00
|
|
|
/// Returns whether the object is Ellipsis, e.g. `...`.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self is ...`.
|
2023-11-15 13:47:00 +00:00
|
|
|
#[deprecated(since = "0.20.0", note = "use `.is(py.Ellipsis())` instead")]
|
2023-01-25 11:05:14 +00:00
|
|
|
pub fn is_ellipsis(&self) -> bool {
|
|
|
|
unsafe { ffi::Py_Ellipsis() == self.as_ptr() }
|
|
|
|
}
|
|
|
|
|
2020-07-21 23:40:31 +00:00
|
|
|
/// Returns whether the object is considered to be true.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `bool(self)`.
|
2023-12-16 10:43:40 +00:00
|
|
|
#[deprecated(since = "0.21.0", note = "use `.is_truthy()` instead")]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn is_true(&self, py: Python<'_>) -> PyResult<bool> {
|
2023-12-16 10:43:40 +00:00
|
|
|
self.is_truthy(py)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns whether the object is considered to be true.
|
|
|
|
///
|
|
|
|
/// This applies truth value testing equivalent to the Python expression `bool(self)`.
|
|
|
|
pub fn is_truthy(&self, py: Python<'_>) -> PyResult<bool> {
|
2020-07-21 23:40:31 +00:00
|
|
|
let v = unsafe { ffi::PyObject_IsTrue(self.as_ptr()) };
|
2021-07-05 13:23:56 +00:00
|
|
|
err::error_on_minusone(py, v)?;
|
|
|
|
Ok(v != 0)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Extracts some type from the Python object.
|
|
|
|
///
|
|
|
|
/// This is a wrapper function around `FromPyObject::extract()`.
|
2024-03-08 07:43:48 +00:00
|
|
|
pub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> PyResult<D>
|
2020-07-21 23:40:31 +00:00
|
|
|
where
|
2024-03-08 07:43:48 +00:00
|
|
|
D: crate::conversion::FromPyObjectBound<'a, 'py>,
|
|
|
|
// TODO it might be possible to relax this bound in future, to allow
|
|
|
|
// e.g. `.extract::<&str>(py)` where `py` is short-lived.
|
|
|
|
'py: 'a,
|
2020-07-21 23:40:31 +00:00
|
|
|
{
|
2024-02-19 22:14:26 +00:00
|
|
|
self.bind(py).as_any().extract()
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Retrieves an attribute value.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self.attr_name`.
|
2022-04-04 20:34:35 +00:00
|
|
|
///
|
2024-01-30 13:28:07 +00:00
|
|
|
/// If calling this method becomes performance-critical, the [`intern!`](crate::intern) macro
|
2022-05-17 18:48:40 +00:00
|
|
|
/// can be used to intern `attr_name`, thereby avoiding repeated temporary allocations of
|
|
|
|
/// Python strings.
|
2022-04-04 20:34:35 +00:00
|
|
|
///
|
2024-01-30 13:28:07 +00:00
|
|
|
/// # Example: `intern!`ing the attribute name
|
2022-04-04 20:34:35 +00:00
|
|
|
///
|
|
|
|
/// ```
|
2024-02-14 00:24:37 +00:00
|
|
|
/// # use pyo3::{prelude::*, intern};
|
2022-04-04 20:34:35 +00:00
|
|
|
/// #
|
|
|
|
/// #[pyfunction]
|
|
|
|
/// fn version(sys: Py<PyModule>, py: Python<'_>) -> PyResult<PyObject> {
|
2024-01-30 13:28:07 +00:00
|
|
|
/// sys.getattr(py, intern!(py, "version"))
|
2022-04-04 20:34:35 +00:00
|
|
|
/// }
|
|
|
|
/// #
|
|
|
|
/// # Python::with_gil(|py| {
|
2024-02-14 00:24:37 +00:00
|
|
|
/// # let sys = py.import_bound("sys").unwrap().unbind();
|
2022-04-04 20:34:35 +00:00
|
|
|
/// # version(sys, py).unwrap();
|
|
|
|
/// # });
|
|
|
|
/// ```
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn getattr<N>(&self, py: Python<'_>, attr_name: N) -> PyResult<PyObject>
|
2020-07-21 23:40:31 +00:00
|
|
|
where
|
2022-05-02 09:13:15 +00:00
|
|
|
N: IntoPy<Py<PyString>>,
|
2020-07-21 23:40:31 +00:00
|
|
|
{
|
2023-12-26 13:16:41 +00:00
|
|
|
self.bind(py).as_any().getattr(attr_name).map(Bound::unbind)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
2021-11-19 15:49:24 +00:00
|
|
|
/// Sets an attribute value.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self.attr_name = value`.
|
2022-04-04 20:34:35 +00:00
|
|
|
///
|
2024-01-30 13:28:07 +00:00
|
|
|
/// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
|
2022-05-17 18:48:40 +00:00
|
|
|
/// macro can be used to intern `attr_name`.
|
2022-04-04 20:34:35 +00:00
|
|
|
///
|
2024-01-30 13:28:07 +00:00
|
|
|
/// # Example: `intern!`ing the attribute name
|
2022-04-04 20:34:35 +00:00
|
|
|
///
|
|
|
|
/// ```
|
2024-01-30 13:28:07 +00:00
|
|
|
/// # use pyo3::{intern, pyfunction, types::PyModule, IntoPy, PyObject, Python, PyResult};
|
2022-04-04 20:34:35 +00:00
|
|
|
/// #
|
|
|
|
/// #[pyfunction]
|
|
|
|
/// fn set_answer(ob: PyObject, py: Python<'_>) -> PyResult<()> {
|
2024-01-30 13:28:07 +00:00
|
|
|
/// ob.setattr(py, intern!(py, "answer"), 42)
|
2022-04-04 20:34:35 +00:00
|
|
|
/// }
|
|
|
|
/// #
|
|
|
|
/// # Python::with_gil(|py| {
|
2024-02-22 09:35:47 +00:00
|
|
|
/// # let ob = PyModule::new_bound(py, "empty").unwrap().into_py(py);
|
2022-04-04 20:34:35 +00:00
|
|
|
/// # set_answer(ob, py).unwrap();
|
|
|
|
/// # });
|
|
|
|
/// ```
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn setattr<N, V>(&self, py: Python<'_>, attr_name: N, value: V) -> PyResult<()>
|
2021-11-19 15:49:24 +00:00
|
|
|
where
|
2022-05-02 09:13:15 +00:00
|
|
|
N: IntoPy<Py<PyString>>,
|
|
|
|
V: IntoPy<Py<PyAny>>,
|
2021-11-19 15:49:24 +00:00
|
|
|
{
|
2023-12-21 13:00:14 +00:00
|
|
|
self.bind(py)
|
2023-09-10 13:51:19 +00:00
|
|
|
.as_any()
|
2023-12-21 13:00:14 +00:00
|
|
|
.setattr(attr_name, value.into_py(py).into_bound(py))
|
2021-11-19 15:49:24 +00:00
|
|
|
}
|
|
|
|
|
2023-12-29 14:43:43 +00:00
|
|
|
/// Deprecated form of [`call_bound`][Py::call_bound].
|
2024-05-01 10:57:03 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
|
|
|
#[deprecated(
|
|
|
|
since = "0.21.0",
|
|
|
|
note = "`call` will be replaced by `call_bound` in a future PyO3 version"
|
2023-12-29 14:43:43 +00:00
|
|
|
)]
|
|
|
|
#[inline]
|
|
|
|
pub fn call<A>(&self, py: Python<'_>, args: A, kwargs: Option<&PyDict>) -> PyResult<PyObject>
|
|
|
|
where
|
|
|
|
A: IntoPy<Py<PyTuple>>,
|
|
|
|
{
|
|
|
|
self.call_bound(py, args, kwargs.map(PyDict::as_borrowed).as_deref())
|
|
|
|
}
|
|
|
|
|
2020-07-21 23:40:31 +00:00
|
|
|
/// Calls the object.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self(*args, **kwargs)`.
|
2023-12-29 14:43:43 +00:00
|
|
|
pub fn call_bound(
|
2020-07-21 23:40:31 +00:00
|
|
|
&self,
|
2022-03-23 07:07:28 +00:00
|
|
|
py: Python<'_>,
|
2020-07-21 23:40:31 +00:00
|
|
|
args: impl IntoPy<Py<PyTuple>>,
|
2023-12-29 14:43:43 +00:00
|
|
|
kwargs: Option<&Bound<'_, PyDict>>,
|
2020-07-21 23:40:31 +00:00
|
|
|
) -> PyResult<PyObject> {
|
2023-12-26 13:16:41 +00:00
|
|
|
self.bind(py).as_any().call(args, kwargs).map(Bound::unbind)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Calls the object with only positional arguments.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self(*args)`.
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn call1(&self, py: Python<'_>, args: impl IntoPy<Py<PyTuple>>) -> PyResult<PyObject> {
|
2023-12-26 13:16:41 +00:00
|
|
|
self.bind(py).as_any().call1(args).map(Bound::unbind)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Calls the object without arguments.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self()`.
|
2022-03-23 07:07:28 +00:00
|
|
|
pub fn call0(&self, py: Python<'_>) -> PyResult<PyObject> {
|
2023-12-26 13:16:41 +00:00
|
|
|
self.bind(py).as_any().call0().map(Bound::unbind)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
2023-12-29 14:43:43 +00:00
|
|
|
/// Deprecated form of [`call_method_bound`][Py::call_method_bound].
|
2024-05-01 10:57:03 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
|
|
|
#[deprecated(
|
|
|
|
since = "0.21.0",
|
|
|
|
note = "`call_method` will be replaced by `call_method_bound` in a future PyO3 version"
|
2023-12-29 14:43:43 +00:00
|
|
|
)]
|
|
|
|
#[inline]
|
|
|
|
pub fn call_method<N, A>(
|
|
|
|
&self,
|
|
|
|
py: Python<'_>,
|
|
|
|
name: N,
|
|
|
|
args: A,
|
|
|
|
kwargs: Option<&PyDict>,
|
|
|
|
) -> PyResult<PyObject>
|
|
|
|
where
|
|
|
|
N: IntoPy<Py<PyString>>,
|
|
|
|
A: IntoPy<Py<PyTuple>>,
|
|
|
|
{
|
|
|
|
self.call_method_bound(py, name, args, kwargs.map(PyDict::as_borrowed).as_deref())
|
|
|
|
}
|
|
|
|
|
2020-07-21 23:40:31 +00:00
|
|
|
/// Calls a method on the object.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self.name(*args, **kwargs)`.
|
2022-05-02 09:13:15 +00:00
|
|
|
///
|
2024-01-30 13:28:07 +00:00
|
|
|
/// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
|
2022-05-17 18:48:40 +00:00
|
|
|
/// macro can be used to intern `name`.
|
2023-12-29 14:43:43 +00:00
|
|
|
pub fn call_method_bound<N, A>(
|
2020-07-21 23:40:31 +00:00
|
|
|
&self,
|
2022-03-23 07:07:28 +00:00
|
|
|
py: Python<'_>,
|
2022-05-02 09:13:15 +00:00
|
|
|
name: N,
|
|
|
|
args: A,
|
2023-12-29 14:43:43 +00:00
|
|
|
kwargs: Option<&Bound<'_, PyDict>>,
|
2022-05-02 09:13:15 +00:00
|
|
|
) -> PyResult<PyObject>
|
|
|
|
where
|
|
|
|
N: IntoPy<Py<PyString>>,
|
|
|
|
A: IntoPy<Py<PyTuple>>,
|
|
|
|
{
|
2023-12-21 13:00:14 +00:00
|
|
|
self.bind(py)
|
2023-09-10 13:51:19 +00:00
|
|
|
.as_any()
|
|
|
|
.call_method(name, args, kwargs)
|
2023-12-26 13:16:41 +00:00
|
|
|
.map(Bound::unbind)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Calls a method on the object with only positional arguments.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self.name(*args)`.
|
2022-05-02 09:13:15 +00:00
|
|
|
///
|
2024-01-30 13:28:07 +00:00
|
|
|
/// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
|
2022-05-17 18:48:40 +00:00
|
|
|
/// macro can be used to intern `name`.
|
2022-05-02 09:13:15 +00:00
|
|
|
pub fn call_method1<N, A>(&self, py: Python<'_>, name: N, args: A) -> PyResult<PyObject>
|
|
|
|
where
|
|
|
|
N: IntoPy<Py<PyString>>,
|
|
|
|
A: IntoPy<Py<PyTuple>>,
|
|
|
|
{
|
2023-12-21 13:00:14 +00:00
|
|
|
self.bind(py)
|
2023-09-10 13:51:19 +00:00
|
|
|
.as_any()
|
|
|
|
.call_method1(name, args)
|
2023-12-26 13:16:41 +00:00
|
|
|
.map(Bound::unbind)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Calls a method on the object with no arguments.
|
|
|
|
///
|
|
|
|
/// This is equivalent to the Python expression `self.name()`.
|
2022-05-02 09:13:15 +00:00
|
|
|
///
|
2024-01-30 13:28:07 +00:00
|
|
|
/// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
|
2022-05-17 18:48:40 +00:00
|
|
|
/// macro can be used to intern `name`.
|
2022-05-02 09:13:15 +00:00
|
|
|
pub fn call_method0<N>(&self, py: Python<'_>, name: N) -> PyResult<PyObject>
|
|
|
|
where
|
|
|
|
N: IntoPy<Py<PyString>>,
|
|
|
|
{
|
2023-12-26 13:16:41 +00:00
|
|
|
self.bind(py).as_any().call_method0(name).map(Bound::unbind)
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
2020-08-06 22:10:52 +00:00
|
|
|
|
|
|
|
/// Create a `Py<T>` instance by taking ownership of the given FFI pointer.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// `ptr` must be a pointer to a Python object of type T.
|
|
|
|
///
|
2021-01-16 13:31:16 +00:00
|
|
|
/// Callers must own the object referred to by `ptr`, as this function
|
|
|
|
/// implicitly takes ownership of that object.
|
|
|
|
///
|
2020-08-06 22:10:52 +00:00
|
|
|
/// # Panics
|
|
|
|
/// Panics if `ptr` is null.
|
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub unsafe fn from_owned_ptr(py: Python<'_>, ptr: *mut ffi::PyObject) -> Py<T> {
|
2020-08-06 22:10:52 +00:00
|
|
|
match NonNull::new(ptr) {
|
|
|
|
Some(nonnull_ptr) => Py(nonnull_ptr, PhantomData),
|
|
|
|
None => crate::err::panic_after_error(py),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a `Py<T>` instance by taking ownership of the given FFI pointer.
|
|
|
|
///
|
2022-05-02 09:13:15 +00:00
|
|
|
/// If `ptr` is null then the current Python exception is fetched as a [`PyErr`].
|
2020-08-06 22:10:52 +00:00
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// If non-null, `ptr` must be a pointer to a Python object of type T.
|
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub unsafe fn from_owned_ptr_or_err(
|
|
|
|
py: Python<'_>,
|
|
|
|
ptr: *mut ffi::PyObject,
|
|
|
|
) -> PyResult<Py<T>> {
|
2020-08-06 22:10:52 +00:00
|
|
|
match NonNull::new(ptr) {
|
|
|
|
Some(nonnull_ptr) => Ok(Py(nonnull_ptr, PhantomData)),
|
2021-10-30 09:51:02 +00:00
|
|
|
None => Err(PyErr::fetch(py)),
|
2020-08-06 22:10:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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.
|
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub unsafe fn from_owned_ptr_or_opt(_py: Python<'_>, ptr: *mut ffi::PyObject) -> Option<Self> {
|
2021-05-06 22:07:19 +00:00
|
|
|
NonNull::new(ptr).map(|nonnull_ptr| Py(nonnull_ptr, PhantomData))
|
2020-08-06 22:10:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a `Py<T>` instance by creating a new reference from the given FFI pointer.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// `ptr` must be a pointer to a Python object of type T.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// Panics if `ptr` is null.
|
|
|
|
#[inline]
|
2024-04-19 11:44:36 +00:00
|
|
|
#[track_caller]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub unsafe fn from_borrowed_ptr(py: Python<'_>, ptr: *mut ffi::PyObject) -> Py<T> {
|
2020-08-06 22:10:52 +00:00
|
|
|
match Self::from_borrowed_ptr_or_opt(py, ptr) {
|
|
|
|
Some(slf) => slf,
|
|
|
|
None => crate::err::panic_after_error(py),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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.
|
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub unsafe fn from_borrowed_ptr_or_err(
|
|
|
|
py: Python<'_>,
|
|
|
|
ptr: *mut ffi::PyObject,
|
|
|
|
) -> PyResult<Self> {
|
2021-10-30 09:51:02 +00:00
|
|
|
Self::from_borrowed_ptr_or_opt(py, ptr).ok_or_else(|| PyErr::fetch(py))
|
2020-08-06 22:10:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a `Py<T>` instance by creating a new reference from the given FFI pointer.
|
|
|
|
///
|
|
|
|
/// If `ptr` is null then `None` is returned.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// `ptr` must be a pointer to a Python object of type T.
|
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
pub unsafe fn from_borrowed_ptr_or_opt(
|
|
|
|
_py: Python<'_>,
|
|
|
|
ptr: *mut ffi::PyObject,
|
|
|
|
) -> Option<Self> {
|
2020-08-06 22:10:52 +00:00
|
|
|
NonNull::new(ptr).map(|nonnull_ptr| {
|
|
|
|
ffi::Py_INCREF(ptr);
|
|
|
|
Py(nonnull_ptr, PhantomData)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// For internal conversions.
|
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
/// `ptr` must point to a Python object of type T.
|
2024-02-01 09:27:44 +00:00
|
|
|
unsafe fn from_non_null(ptr: NonNull<ffi::PyObject>) -> Self {
|
2020-08-06 22:10:52 +00:00
|
|
|
Self(ptr, PhantomData)
|
|
|
|
}
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
|
|
|
|
2017-06-20 06:57:34 +00:00
|
|
|
impl<T> ToPyObject for Py<T> {
|
2017-07-18 17:13:50 +00:00
|
|
|
/// Converts `Py` instance -> PyObject.
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
fn to_object(&self, py: Python<'_>) -> PyObject {
|
2024-02-01 09:27:44 +00:00
|
|
|
self.clone_ref(py).into_any()
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-24 17:21:45 +00:00
|
|
|
impl<T> IntoPy<PyObject> for Py<T> {
|
2020-03-17 14:16:15 +00:00
|
|
|
/// Converts a `Py` instance to `PyObject`.
|
|
|
|
/// Consumes `self` without calling `Py_DECREF()`.
|
2017-06-20 03:55:07 +00:00
|
|
|
#[inline]
|
2022-03-23 07:07:28 +00:00
|
|
|
fn into_py(self, _py: Python<'_>) -> PyObject {
|
2024-02-01 09:27:44 +00:00
|
|
|
self.into_any()
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-16 11:33:40 +00:00
|
|
|
impl<T> IntoPy<PyObject> for &'_ Py<T> {
|
|
|
|
#[inline]
|
|
|
|
fn into_py(self, py: Python<'_>) -> PyObject {
|
|
|
|
self.to_object(py)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<T> ToPyObject for Bound<'_, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
/// Converts `&Bound` instance -> PyObject, increasing the reference count.
|
|
|
|
#[inline]
|
2023-09-10 13:51:19 +00:00
|
|
|
fn to_object(&self, py: Python<'_>) -> PyObject {
|
2024-02-01 09:27:44 +00:00
|
|
|
self.clone().into_py(py)
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<T> IntoPy<PyObject> for Bound<'_, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
/// Converts a `Bound` instance to `PyObject`.
|
2023-09-10 13:51:19 +00:00
|
|
|
#[inline]
|
|
|
|
fn into_py(self, _py: Python<'_>) -> PyObject {
|
2023-11-28 10:40:37 +00:00
|
|
|
self.into_any().unbind()
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<T> IntoPy<PyObject> for &Bound<'_, T> {
|
2024-02-01 09:27:44 +00:00
|
|
|
/// Converts `&Bound` instance -> PyObject, increasing the reference count.
|
2023-09-10 13:51:19 +00:00
|
|
|
#[inline]
|
2024-02-01 09:27:44 +00:00
|
|
|
fn into_py(self, py: Python<'_>) -> PyObject {
|
|
|
|
self.to_object(py)
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-30 18:40:52 +00:00
|
|
|
unsafe impl<T> crate::AsPyPointer for Py<T> {
|
2017-06-20 03:55:07 +00:00
|
|
|
/// Gets the underlying FFI pointer, returns a borrowed pointer.
|
|
|
|
#[inline]
|
|
|
|
fn as_ptr(&self) -> *mut ffi::PyObject {
|
2018-11-08 15:09:52 +00:00
|
|
|
self.0.as_ptr()
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-12 18:30:08 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2020-07-21 23:40:31 +00:00
|
|
|
impl<T> std::convert::From<&'_ T> for PyObject
|
2020-02-02 06:28:44 +00:00
|
|
|
where
|
2024-02-01 09:27:44 +00:00
|
|
|
T: PyNativeType,
|
2020-02-02 06:28:44 +00:00
|
|
|
{
|
2024-02-01 09:27:44 +00:00
|
|
|
#[inline]
|
2020-07-21 23:40:31 +00:00
|
|
|
fn from(obj: &T) -> Self {
|
2024-02-01 09:27:44 +00:00
|
|
|
obj.as_borrowed().to_owned().into_any().unbind()
|
2020-02-02 06:28:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-21 23:40:31 +00:00
|
|
|
impl<T> std::convert::From<Py<T>> for PyObject
|
|
|
|
where
|
|
|
|
T: AsRef<PyAny>,
|
|
|
|
{
|
2020-11-28 10:34:09 +00:00
|
|
|
#[inline]
|
2020-07-21 23:40:31 +00:00
|
|
|
fn from(other: Py<T>) -> Self {
|
2024-02-01 09:27:44 +00:00
|
|
|
other.into_any()
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<T> std::convert::From<Bound<'_, T>> for PyObject
|
2023-09-10 13:51:19 +00:00
|
|
|
where
|
|
|
|
T: AsRef<PyAny>,
|
|
|
|
{
|
|
|
|
#[inline]
|
2023-12-21 12:04:45 +00:00
|
|
|
fn from(other: Bound<'_, T>) -> Self {
|
2023-09-10 13:51:19 +00:00
|
|
|
let py = other.py();
|
|
|
|
other.into_py(py)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 12:04:45 +00:00
|
|
|
impl<T> std::convert::From<Bound<'_, T>> for Py<T> {
|
2023-09-10 13:51:19 +00:00
|
|
|
#[inline]
|
2023-12-21 12:04:45 +00:00
|
|
|
fn from(other: Bound<'_, T>) -> Self {
|
2023-12-26 13:16:41 +00:00
|
|
|
other.unbind()
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-03 13:25:16 +00:00
|
|
|
// `&PyCell<T>` can be converted to `Py<T>`
|
2024-05-01 10:57:03 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2024-03-03 14:47:25 +00:00
|
|
|
#[allow(deprecated)]
|
|
|
|
impl<T> std::convert::From<&crate::PyCell<T>> for Py<T>
|
2019-12-14 14:16:39 +00:00
|
|
|
where
|
|
|
|
T: PyClass,
|
|
|
|
{
|
2024-03-03 14:47:25 +00:00
|
|
|
fn from(cell: &crate::PyCell<T>) -> Self {
|
2024-02-01 09:27:44 +00:00
|
|
|
cell.as_borrowed().to_owned().unbind()
|
2019-12-14 14:16:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-15 15:24:38 +00:00
|
|
|
impl<'a, T> std::convert::From<PyRef<'a, T>> for Py<T>
|
2019-12-14 14:16:39 +00:00
|
|
|
where
|
|
|
|
T: PyClass,
|
|
|
|
{
|
2020-02-15 15:24:38 +00:00
|
|
|
fn from(pyref: PyRef<'a, T>) -> Self {
|
2020-06-10 07:46:39 +00:00
|
|
|
unsafe { Py::from_borrowed_ptr(pyref.py(), pyref.as_ptr()) }
|
2020-02-15 15:24:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, T> std::convert::From<PyRefMut<'a, T>> for Py<T>
|
|
|
|
where
|
2022-06-11 11:20:43 +00:00
|
|
|
T: PyClass<Frozen = False>,
|
2020-02-15 15:24:38 +00:00
|
|
|
{
|
|
|
|
fn from(pyref: PyRefMut<'a, T>) -> Self {
|
2020-06-10 07:46:39 +00:00
|
|
|
unsafe { Py::from_borrowed_ptr(pyref.py(), pyref.as_ptr()) }
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-03 01:31:05 +00:00
|
|
|
/// If the GIL is held this increments `self`'s reference count.
|
2024-05-11 14:48:45 +00:00
|
|
|
/// Otherwise, it will panic.
|
|
|
|
///
|
|
|
|
/// Only available if the `py-clone` feature is enabled.
|
|
|
|
#[cfg(feature = "py-clone")]
|
2020-05-06 08:04:57 +00:00
|
|
|
impl<T> Clone for Py<T> {
|
2024-05-11 14:48:45 +00:00
|
|
|
#[track_caller]
|
2020-05-06 08:04:57 +00:00
|
|
|
fn clone(&self) -> Self {
|
|
|
|
unsafe {
|
|
|
|
gil::register_incref(self.0);
|
|
|
|
}
|
|
|
|
Self(self.0, PhantomData)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-11 14:48:45 +00:00
|
|
|
/// 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.
|
2017-06-20 06:57:34 +00:00
|
|
|
impl<T> Drop for Py<T> {
|
2024-05-11 14:48:45 +00:00
|
|
|
#[track_caller]
|
2017-06-20 03:55:07 +00:00
|
|
|
fn drop(&mut self) {
|
2018-07-30 21:01:46 +00:00
|
|
|
unsafe {
|
2020-05-06 08:04:57 +00:00
|
|
|
gil::register_decref(self.0);
|
2018-07-30 21:01:46 +00:00
|
|
|
}
|
2017-06-20 03:55:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-29 13:31:04 +00:00
|
|
|
impl<T> FromPyObject<'_> for Py<T>
|
2018-07-30 21:01:46 +00:00
|
|
|
where
|
2024-01-29 13:31:04 +00:00
|
|
|
T: PyTypeCheck,
|
2017-06-23 03:56:09 +00:00
|
|
|
{
|
|
|
|
/// Extracts `Self` from the source `PyObject`.
|
2024-01-29 13:31:04 +00:00
|
|
|
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> {
|
|
|
|
ob.extract::<Bound<'_, T>>().map(Bound::unbind)
|
2017-06-23 03:56:09 +00:00
|
|
|
}
|
|
|
|
}
|
2019-02-23 17:01:22 +00:00
|
|
|
|
2024-01-29 13:31:04 +00:00
|
|
|
impl<'py, T> FromPyObject<'py> for Bound<'py, T>
|
2023-09-10 13:51:19 +00:00
|
|
|
where
|
2024-01-29 13:31:04 +00:00
|
|
|
T: PyTypeCheck,
|
2023-09-10 13:51:19 +00:00
|
|
|
{
|
|
|
|
/// Extracts `Self` from the source `PyObject`.
|
2024-01-29 13:31:04 +00:00
|
|
|
fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
|
2024-05-01 10:57:03 +00:00
|
|
|
ob.downcast().cloned().map_err(Into::into)
|
2023-09-10 13:51:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-13 05:33:11 +00:00
|
|
|
/// `Py<T>` can be used as an error when T is an Error.
|
2020-05-24 12:38:27 +00:00
|
|
|
///
|
2022-10-13 05:33:11 +00:00
|
|
|
/// However for GIL lifetime reasons, cause() cannot be implemented for `Py<T>`.
|
2020-05-24 12:38:27 +00:00
|
|
|
/// Use .as_ref() to get the GIL-scoped error if you need to inspect the cause.
|
2024-05-12 18:30:08 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2020-05-24 12:38:27 +00:00
|
|
|
impl<T> std::error::Error for Py<T>
|
|
|
|
where
|
|
|
|
T: std::error::Error + PyTypeInfo,
|
2020-07-04 15:55:26 +00:00
|
|
|
T::AsRefTarget: std::fmt::Display,
|
|
|
|
{
|
|
|
|
}
|
2020-05-24 12:38:27 +00:00
|
|
|
|
|
|
|
impl<T> std::fmt::Display for Py<T>
|
|
|
|
where
|
|
|
|
T: PyTypeInfo,
|
|
|
|
{
|
2022-03-23 07:07:28 +00:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2024-02-18 00:09:56 +00:00
|
|
|
Python::with_gil(|py| std::fmt::Display::fmt(self.bind(py), f))
|
2020-05-24 12:38:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> std::fmt::Debug for Py<T> {
|
2022-03-23 07:07:28 +00:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2020-05-24 12:38:27 +00:00
|
|
|
f.debug_tuple("Py").field(&self.0.as_ptr()).finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-06 21:29:05 +00:00
|
|
|
/// 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`](struct.Py.html).
|
2020-07-21 23:40:31 +00:00
|
|
|
pub type PyObject = Py<PyAny>;
|
|
|
|
|
2020-08-06 22:10:52 +00:00
|
|
|
impl PyObject {
|
2024-02-18 01:11:43 +00:00
|
|
|
/// Deprecated form of [`PyObject::downcast_bound`]
|
2024-05-01 10:57:03 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
|
|
|
#[deprecated(
|
|
|
|
since = "0.21.0",
|
|
|
|
note = "`PyObject::downcast` will be replaced by `PyObject::downcast_bound` in a future PyO3 version"
|
2024-02-18 01:11:43 +00:00
|
|
|
)]
|
|
|
|
#[inline]
|
2024-05-01 10:57:03 +00:00
|
|
|
pub fn downcast<'py, T>(
|
|
|
|
&'py self,
|
|
|
|
py: Python<'py>,
|
|
|
|
) -> Result<&'py T, crate::err::PyDowncastError<'py>>
|
2024-02-18 01:11:43 +00:00
|
|
|
where
|
|
|
|
T: PyTypeCheck<AsRefTarget = T>,
|
|
|
|
{
|
|
|
|
self.downcast_bound::<T>(py)
|
|
|
|
.map(Bound::as_gil_ref)
|
2024-05-01 10:57:03 +00:00
|
|
|
.map_err(crate::err::PyDowncastError::from_downcast_err)
|
2024-02-18 01:11:43 +00:00
|
|
|
}
|
2023-01-24 18:15:32 +00:00
|
|
|
/// Downcast this `PyObject` to a concrete Python type or pyclass.
|
2020-08-06 22:10:52 +00:00
|
|
|
///
|
2023-01-24 18:15:32 +00:00
|
|
|
/// 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`](struct.Py.html#method.extract).
|
|
|
|
///
|
|
|
|
/// # Example: Downcasting to a specific Python object
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use pyo3::prelude::*;
|
|
|
|
/// use pyo3::types::{PyDict, PyList};
|
|
|
|
///
|
|
|
|
/// Python::with_gil(|py| {
|
2024-02-11 23:55:56 +00:00
|
|
|
/// let any: PyObject = PyDict::new_bound(py).into();
|
2023-01-24 18:15:32 +00:00
|
|
|
///
|
2024-02-18 01:11:43 +00:00
|
|
|
/// assert!(any.downcast_bound::<PyDict>(py).is_ok());
|
|
|
|
/// assert!(any.downcast_bound::<PyList>(py).is_err());
|
2023-01-24 18:15:32 +00:00
|
|
|
/// });
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Example: Getting a reference to a pyclass
|
|
|
|
///
|
|
|
|
/// This is useful if you want to mutate a `PyObject` that
|
|
|
|
/// might actually be a pyclass.
|
2020-08-06 22:10:52 +00:00
|
|
|
///
|
2023-01-28 14:35:31 +00:00
|
|
|
/// ```rust
|
2023-01-24 18:15:32 +00:00
|
|
|
/// # fn main() -> Result<(), pyo3::PyErr> {
|
|
|
|
/// 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);
|
|
|
|
///
|
2024-02-18 01:11:43 +00:00
|
|
|
/// let class_bound = class.downcast_bound::<Class>(py)?;
|
2023-01-24 18:15:32 +00:00
|
|
|
///
|
2024-02-18 01:11:43 +00:00
|
|
|
/// class_bound.borrow_mut().i += 1;
|
2023-01-28 14:35:31 +00:00
|
|
|
///
|
|
|
|
/// // Alternatively you can get a `PyRefMut` directly
|
|
|
|
/// let class_ref: PyRefMut<'_, Class> = class.extract(py)?;
|
|
|
|
/// assert_eq!(class_ref.i, 1);
|
2023-01-24 18:15:32 +00:00
|
|
|
/// Ok(())
|
|
|
|
/// })
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2022-11-19 08:08:51 +00:00
|
|
|
#[inline]
|
2024-02-18 01:11:43 +00:00
|
|
|
pub fn downcast_bound<'py, T>(
|
|
|
|
&self,
|
|
|
|
py: Python<'py>,
|
|
|
|
) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>
|
2022-11-14 06:15:33 +00:00
|
|
|
where
|
2024-02-18 01:11:43 +00:00
|
|
|
T: PyTypeCheck,
|
2022-11-14 06:15:33 +00:00
|
|
|
{
|
2024-02-18 01:11:43 +00:00
|
|
|
self.bind(py).downcast()
|
2022-11-14 06:15:33 +00:00
|
|
|
}
|
|
|
|
|
2024-02-18 01:11:43 +00:00
|
|
|
/// Deprecated form of [`PyObject::downcast_bound_unchecked`]
|
2022-11-17 09:42:52 +00:00
|
|
|
///
|
|
|
|
/// # Safety
|
|
|
|
///
|
|
|
|
/// Callers must ensure that the type is valid or risk type confusion.
|
2024-05-01 10:57:03 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
|
|
|
#[deprecated(
|
|
|
|
since = "0.21.0",
|
|
|
|
note = "`PyObject::downcast_unchecked` will be replaced by `PyObject::downcast_bound_unchecked` in a future PyO3 version"
|
2024-02-18 01:11:43 +00:00
|
|
|
)]
|
2022-11-19 08:08:51 +00:00
|
|
|
#[inline]
|
2024-02-18 01:11:43 +00:00
|
|
|
pub unsafe fn downcast_unchecked<'py, T>(&'py self, py: Python<'py>) -> &T
|
2022-11-17 09:42:52 +00:00
|
|
|
where
|
2023-11-27 20:19:44 +00:00
|
|
|
T: HasPyGilRef<AsRefTarget = T>,
|
2022-11-17 09:42:52 +00:00
|
|
|
{
|
2024-02-18 01:11:43 +00:00
|
|
|
self.downcast_bound_unchecked::<T>(py).as_gil_ref()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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.
|
|
|
|
#[inline]
|
|
|
|
pub unsafe fn downcast_bound_unchecked<'py, T>(&self, py: Python<'py>) -> &Bound<'py, T> {
|
|
|
|
self.bind(py).downcast_unchecked()
|
2022-11-17 09:42:52 +00:00
|
|
|
}
|
2020-08-06 22:10:52 +00:00
|
|
|
}
|
|
|
|
|
2019-02-23 17:01:22 +00:00
|
|
|
#[cfg(test)]
|
2021-07-26 17:19:53 +00:00
|
|
|
mod tests {
|
2023-12-21 12:04:45 +00:00
|
|
|
use super::{Bound, Py, PyObject};
|
2024-02-22 09:35:47 +00:00
|
|
|
use crate::types::any::PyAnyMethods;
|
2023-12-29 14:43:43 +00:00
|
|
|
use crate::types::{dict::IntoPyDict, PyDict, PyString};
|
2024-03-20 12:52:09 +00:00
|
|
|
use crate::types::{PyCapsule, PyStringMethods};
|
2024-05-01 10:57:03 +00:00
|
|
|
use crate::{ffi, Borrowed, PyAny, PyResult, Python, ToPyObject};
|
2022-02-05 00:31:37 +00:00
|
|
|
|
|
|
|
#[test]
|
2023-12-29 14:43:43 +00:00
|
|
|
fn test_call() {
|
2022-02-05 00:31:37 +00:00
|
|
|
Python::with_gil(|py| {
|
2024-05-01 10:57:03 +00:00
|
|
|
let obj = py.get_type_bound::<PyDict>().to_object(py);
|
2023-12-29 14:43:43 +00:00
|
|
|
|
2024-05-01 10:57:03 +00:00
|
|
|
let assert_repr = |obj: &Bound<'_, PyAny>, expected: &str| {
|
|
|
|
assert_eq!(obj.repr().unwrap().to_cow().unwrap(), expected);
|
2023-12-29 14:43:43 +00:00
|
|
|
};
|
|
|
|
|
2024-05-01 10:57:03 +00:00
|
|
|
assert_repr(obj.call0(py).unwrap().bind(py), "{}");
|
|
|
|
assert_repr(obj.call1(py, ()).unwrap().bind(py), "{}");
|
|
|
|
assert_repr(obj.call_bound(py, (), None).unwrap().bind(py), "{}");
|
2023-12-29 14:43:43 +00:00
|
|
|
|
2024-05-01 10:57:03 +00:00
|
|
|
assert_repr(obj.call1(py, ((('x', 1),),)).unwrap().bind(py), "{'x': 1}");
|
2023-12-29 14:43:43 +00:00
|
|
|
assert_repr(
|
2024-02-10 12:59:55 +00:00
|
|
|
obj.call_bound(py, (), Some(&[('x', 1)].into_py_dict_bound(py)))
|
2022-02-05 00:31:37 +00:00
|
|
|
.unwrap()
|
2024-05-01 10:57:03 +00:00
|
|
|
.bind(py),
|
2023-12-29 14:43:43 +00:00
|
|
|
"{'x': 1}",
|
2022-02-05 00:31:37 +00:00
|
|
|
);
|
|
|
|
})
|
|
|
|
}
|
2020-07-21 23:40:31 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_call_for_non_existing_method() {
|
2021-08-12 00:47:41 +00:00
|
|
|
Python::with_gil(|py| {
|
2024-04-23 05:48:27 +00:00
|
|
|
let obj: PyObject = PyDict::new_bound(py).into();
|
2021-08-12 00:47:41 +00:00
|
|
|
assert!(obj.call_method0(py, "asdf").is_err());
|
|
|
|
assert!(obj
|
2024-05-01 10:57:03 +00:00
|
|
|
.call_method_bound(py, "nonexistent_method", (1,), None)
|
2021-08-12 00:47:41 +00:00
|
|
|
.is_err());
|
|
|
|
assert!(obj.call_method0(py, "nonexistent_method").is_err());
|
|
|
|
assert!(obj.call_method1(py, "nonexistent_method", (1,)).is_err());
|
|
|
|
});
|
2020-07-21 23:40:31 +00:00
|
|
|
}
|
2020-02-02 06:28:44 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn py_from_dict() {
|
2021-08-12 09:52:56 +00:00
|
|
|
let dict: Py<PyDict> = Python::with_gil(|py| {
|
2024-04-23 05:48:27 +00:00
|
|
|
let native = PyDict::new_bound(py);
|
2020-02-02 06:28:44 +00:00
|
|
|
Py::from(native)
|
2021-08-12 00:47:41 +00:00
|
|
|
});
|
|
|
|
|
2024-05-11 14:48:45 +00:00
|
|
|
Python::with_gil(move |py| {
|
|
|
|
assert_eq!(dict.get_refcnt(py), 1);
|
|
|
|
});
|
2020-02-02 06:28:44 +00:00
|
|
|
}
|
2020-11-28 10:34:09 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn pyobject_from_py() {
|
|
|
|
Python::with_gil(|py| {
|
2024-04-23 05:48:27 +00:00
|
|
|
let dict: Py<PyDict> = PyDict::new_bound(py).unbind();
|
2020-11-28 10:34:09 +00:00
|
|
|
let cnt = dict.get_refcnt(py);
|
|
|
|
let p: PyObject = dict.into();
|
|
|
|
assert_eq!(p.get_refcnt(py), cnt);
|
|
|
|
});
|
|
|
|
}
|
2022-05-02 09:13:15 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn attr() -> PyResult<()> {
|
|
|
|
use crate::types::PyModule;
|
|
|
|
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
const CODE: &str = r#"
|
|
|
|
class A:
|
|
|
|
pass
|
|
|
|
a = A()
|
|
|
|
"#;
|
2024-02-22 09:35:47 +00:00
|
|
|
let module = PyModule::from_code_bound(py, CODE, "", "")?;
|
2022-05-02 09:13:15 +00:00
|
|
|
let instance: Py<PyAny> = module.getattr("a")?.into();
|
|
|
|
|
|
|
|
instance.getattr(py, "foo").unwrap_err();
|
|
|
|
|
|
|
|
instance.setattr(py, "foo", "bar")?;
|
|
|
|
|
|
|
|
assert!(instance
|
|
|
|
.getattr(py, "foo")?
|
2024-05-01 10:57:03 +00:00
|
|
|
.bind(py)
|
2023-11-21 11:41:43 +00:00
|
|
|
.eq(PyString::new_bound(py, "bar"))?);
|
2022-05-02 09:13:15 +00:00
|
|
|
|
|
|
|
instance.getattr(py, "foo")?;
|
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn pystring_attr() -> PyResult<()> {
|
|
|
|
use crate::types::PyModule;
|
|
|
|
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
const CODE: &str = r#"
|
|
|
|
class A:
|
|
|
|
pass
|
|
|
|
a = A()
|
|
|
|
"#;
|
2024-02-22 09:35:47 +00:00
|
|
|
let module = PyModule::from_code_bound(py, CODE, "", "")?;
|
2022-05-02 09:13:15 +00:00
|
|
|
let instance: Py<PyAny> = module.getattr("a")?.into();
|
|
|
|
|
2024-01-30 13:28:07 +00:00
|
|
|
let foo = crate::intern!(py, "foo");
|
|
|
|
let bar = crate::intern!(py, "bar");
|
2022-05-02 09:13:15 +00:00
|
|
|
|
|
|
|
instance.getattr(py, foo).unwrap_err();
|
|
|
|
instance.setattr(py, foo, bar)?;
|
2024-05-01 10:57:03 +00:00
|
|
|
assert!(instance.getattr(py, foo)?.bind(py).eq(bar)?);
|
2022-05-02 09:13:15 +00:00
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn invalid_attr() -> PyResult<()> {
|
|
|
|
Python::with_gil(|py| {
|
2024-05-01 10:57:03 +00:00
|
|
|
let instance: Py<PyAny> = py.eval_bound("object()", None, None)?.into();
|
2022-05-02 09:13:15 +00:00
|
|
|
|
|
|
|
instance.getattr(py, "foo").unwrap_err();
|
|
|
|
|
|
|
|
// Cannot assign arbitrary attributes to `object`
|
|
|
|
instance.setattr(py, "foo", "bar").unwrap_err();
|
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
}
|
2022-06-12 07:51:47 +00:00
|
|
|
|
2023-09-10 13:51:19 +00:00
|
|
|
#[test]
|
|
|
|
fn test_py2_from_py_object() {
|
|
|
|
Python::with_gil(|py| {
|
2024-05-01 10:57:03 +00:00
|
|
|
let instance = py.eval_bound("object()", None, None).unwrap();
|
2023-09-10 13:51:19 +00:00
|
|
|
let ptr = instance.as_ptr();
|
2023-12-21 12:04:45 +00:00
|
|
|
let instance: Bound<'_, PyAny> = instance.extract().unwrap();
|
2023-09-10 13:51:19 +00:00
|
|
|
assert_eq!(instance.as_ptr(), ptr);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_py2_into_py_object() {
|
|
|
|
Python::with_gil(|py| {
|
2023-12-23 21:48:04 +00:00
|
|
|
let instance = py
|
2024-05-01 10:57:03 +00:00
|
|
|
.eval_bound("object()", None, None)
|
2023-12-23 21:48:04 +00:00
|
|
|
.unwrap()
|
|
|
|
.as_borrowed()
|
|
|
|
.to_owned();
|
2023-09-10 13:51:19 +00:00
|
|
|
let ptr = instance.as_ptr();
|
2023-12-26 13:16:41 +00:00
|
|
|
let instance: PyObject = instance.clone().unbind();
|
2023-09-10 13:51:19 +00:00
|
|
|
assert_eq!(instance.as_ptr(), ptr);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-01-25 11:05:14 +00:00
|
|
|
#[test]
|
2023-11-15 13:47:00 +00:00
|
|
|
#[allow(deprecated)]
|
2023-01-25 11:05:14 +00:00
|
|
|
fn test_is_ellipsis() {
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let v = py
|
2024-05-09 22:21:48 +00:00
|
|
|
.eval_bound("...", None, None)
|
2023-07-21 13:30:02 +00:00
|
|
|
.map_err(|e| e.display(py))
|
2023-01-25 11:05:14 +00:00
|
|
|
.unwrap()
|
|
|
|
.to_object(py);
|
|
|
|
|
|
|
|
assert!(v.is_ellipsis());
|
|
|
|
|
|
|
|
let not_ellipsis = 5.to_object(py);
|
|
|
|
assert!(!not_ellipsis.is_ellipsis());
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-09-10 13:51:19 +00:00
|
|
|
#[test]
|
|
|
|
fn test_debug_fmt() {
|
|
|
|
Python::with_gil(|py| {
|
2023-12-21 13:00:14 +00:00
|
|
|
let obj = "hello world".to_object(py).into_bound(py);
|
2023-09-10 13:51:19 +00:00
|
|
|
assert_eq!(format!("{:?}", obj), "'hello world'");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_display_fmt() {
|
|
|
|
Python::with_gil(|py| {
|
2023-12-21 13:00:14 +00:00
|
|
|
let obj = "hello world".to_object(py).into_bound(py);
|
2023-09-10 13:51:19 +00:00
|
|
|
assert_eq!(format!("{}", obj), "hello world");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-11-28 10:40:37 +00:00
|
|
|
#[test]
|
|
|
|
fn test_bound_as_any() {
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let obj = PyString::new_bound(py, "hello world");
|
|
|
|
let any = obj.as_any();
|
|
|
|
assert_eq!(any.as_ptr(), obj.as_ptr());
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_bound_into_any() {
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let obj = PyString::new_bound(py, "hello world");
|
|
|
|
let any = obj.clone().into_any();
|
|
|
|
assert_eq!(any.as_ptr(), obj.as_ptr());
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-03-20 12:52:09 +00:00
|
|
|
#[test]
|
|
|
|
fn test_bound_py_conversions() {
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let obj: Bound<'_, PyString> = PyString::new_bound(py, "hello world");
|
|
|
|
let obj_unbound: &Py<PyString> = obj.as_unbound();
|
|
|
|
let _: &Bound<'_, PyString> = obj_unbound.bind(py);
|
|
|
|
|
|
|
|
let obj_unbound: Py<PyString> = obj.unbind();
|
|
|
|
let obj: Bound<'_, PyString> = obj_unbound.into_bound(py);
|
|
|
|
|
|
|
|
assert_eq!(obj.to_cow().unwrap(), "hello world");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-02-18 22:03:43 +00:00
|
|
|
#[test]
|
|
|
|
fn bound_from_borrowed_ptr_constructors() {
|
|
|
|
// More detailed tests of the underlying semantics in pycell.rs
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
fn check_drop<'py>(
|
|
|
|
py: Python<'py>,
|
|
|
|
method: impl FnOnce(*mut ffi::PyObject) -> Bound<'py, PyAny>,
|
|
|
|
) {
|
|
|
|
let mut dropped = false;
|
|
|
|
let capsule = PyCapsule::new_bound_with_destructor(
|
|
|
|
py,
|
|
|
|
(&mut dropped) as *mut _ as usize,
|
|
|
|
None,
|
|
|
|
|ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) },
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let bound = method(capsule.as_ptr());
|
|
|
|
assert!(!dropped);
|
|
|
|
|
|
|
|
// creating the bound should have increased the refcount
|
|
|
|
drop(capsule);
|
|
|
|
assert!(!dropped);
|
|
|
|
|
|
|
|
// dropping the bound should now also decrease the refcount and free the object
|
|
|
|
drop(bound);
|
|
|
|
assert!(dropped);
|
|
|
|
}
|
|
|
|
|
|
|
|
check_drop(py, |ptr| unsafe { Bound::from_borrowed_ptr(py, ptr) });
|
|
|
|
check_drop(py, |ptr| unsafe {
|
|
|
|
Bound::from_borrowed_ptr_or_opt(py, ptr).unwrap()
|
|
|
|
});
|
|
|
|
check_drop(py, |ptr| unsafe {
|
|
|
|
Bound::from_borrowed_ptr_or_err(py, ptr).unwrap()
|
|
|
|
});
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn borrowed_ptr_constructors() {
|
|
|
|
// More detailed tests of the underlying semantics in pycell.rs
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
fn check_drop<'py>(
|
|
|
|
py: Python<'py>,
|
|
|
|
method: impl FnOnce(&*mut ffi::PyObject) -> Borrowed<'_, 'py, PyAny>,
|
|
|
|
) {
|
|
|
|
let mut dropped = false;
|
|
|
|
let capsule = PyCapsule::new_bound_with_destructor(
|
|
|
|
py,
|
|
|
|
(&mut dropped) as *mut _ as usize,
|
|
|
|
None,
|
|
|
|
|ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) },
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let ptr = &capsule.as_ptr();
|
|
|
|
let _borrowed = method(ptr);
|
|
|
|
assert!(!dropped);
|
|
|
|
|
|
|
|
// creating the borrow should not have increased the refcount
|
|
|
|
drop(capsule);
|
|
|
|
assert!(dropped);
|
|
|
|
}
|
|
|
|
|
|
|
|
check_drop(py, |&ptr| unsafe { Borrowed::from_ptr(py, ptr) });
|
|
|
|
check_drop(py, |&ptr| unsafe {
|
|
|
|
Borrowed::from_ptr_or_opt(py, ptr).unwrap()
|
|
|
|
});
|
|
|
|
check_drop(py, |&ptr| unsafe {
|
|
|
|
Borrowed::from_ptr_or_err(py, ptr).unwrap()
|
|
|
|
});
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-02-21 22:56:03 +00:00
|
|
|
#[test]
|
|
|
|
fn explicit_drop_ref() {
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let object: Py<PyDict> = PyDict::new_bound(py).unbind();
|
|
|
|
let object2 = object.clone_ref(py);
|
|
|
|
|
|
|
|
assert_eq!(object.as_ptr(), object2.as_ptr());
|
|
|
|
assert_eq!(object.get_refcnt(py), 2);
|
|
|
|
|
|
|
|
object.drop_ref(py);
|
|
|
|
|
|
|
|
assert_eq!(object2.get_refcnt(py), 1);
|
|
|
|
|
|
|
|
object2.drop_ref(py);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-06-12 07:51:47 +00:00
|
|
|
#[cfg(feature = "macros")]
|
|
|
|
mod using_macros {
|
|
|
|
use super::*;
|
|
|
|
|
2023-11-28 14:45:45 +00:00
|
|
|
#[crate::pyclass(crate = "crate")]
|
2022-06-12 07:51:47 +00:00
|
|
|
struct SomeClass(i32);
|
|
|
|
|
|
|
|
#[test]
|
2023-11-28 14:45:45 +00:00
|
|
|
fn py_borrow_methods() {
|
2022-06-12 07:51:47 +00:00
|
|
|
// More detailed tests of the underlying semantics in pycell.rs
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let instance = Py::new(py, SomeClass(0)).unwrap();
|
|
|
|
assert_eq!(instance.borrow(py).0, 0);
|
|
|
|
assert_eq!(instance.try_borrow(py).unwrap().0, 0);
|
|
|
|
assert_eq!(instance.borrow_mut(py).0, 0);
|
|
|
|
assert_eq!(instance.try_borrow_mut(py).unwrap().0, 0);
|
|
|
|
|
|
|
|
instance.borrow_mut(py).0 = 123;
|
|
|
|
|
|
|
|
assert_eq!(instance.borrow(py).0, 123);
|
|
|
|
assert_eq!(instance.try_borrow(py).unwrap().0, 123);
|
|
|
|
assert_eq!(instance.borrow_mut(py).0, 123);
|
|
|
|
assert_eq!(instance.try_borrow_mut(py).unwrap().0, 123);
|
|
|
|
})
|
|
|
|
}
|
2023-11-27 20:19:44 +00:00
|
|
|
|
2023-11-28 14:45:45 +00:00
|
|
|
#[test]
|
|
|
|
fn bound_borrow_methods() {
|
|
|
|
// More detailed tests of the underlying semantics in pycell.rs
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let instance = Bound::new(py, SomeClass(0)).unwrap();
|
|
|
|
assert_eq!(instance.borrow().0, 0);
|
|
|
|
assert_eq!(instance.try_borrow().unwrap().0, 0);
|
|
|
|
assert_eq!(instance.borrow_mut().0, 0);
|
|
|
|
assert_eq!(instance.try_borrow_mut().unwrap().0, 0);
|
|
|
|
|
|
|
|
instance.borrow_mut().0 = 123;
|
|
|
|
|
|
|
|
assert_eq!(instance.borrow().0, 123);
|
|
|
|
assert_eq!(instance.try_borrow().unwrap().0, 123);
|
|
|
|
assert_eq!(instance.borrow_mut().0, 123);
|
|
|
|
assert_eq!(instance.try_borrow_mut().unwrap().0, 123);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[crate::pyclass(frozen, crate = "crate")]
|
|
|
|
struct FrozenClass(i32);
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_frozen_get() {
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
for i in 0..10 {
|
|
|
|
let instance = Py::new(py, FrozenClass(i)).unwrap();
|
|
|
|
assert_eq!(instance.get().0, i);
|
|
|
|
|
|
|
|
assert_eq!(instance.bind(py).get().0, i);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-11-27 20:19:44 +00:00
|
|
|
#[test]
|
2024-04-28 21:03:51 +00:00
|
|
|
#[cfg(feature = "gil-refs")]
|
2023-11-27 21:27:34 +00:00
|
|
|
#[allow(deprecated)]
|
2023-11-27 20:19:44 +00:00
|
|
|
fn cell_tryfrom() {
|
2024-04-28 21:03:51 +00:00
|
|
|
use crate::{PyCell, PyTryInto};
|
2023-11-27 20:19:44 +00:00
|
|
|
// More detailed tests of the underlying semantics in pycell.rs
|
|
|
|
Python::with_gil(|py| {
|
|
|
|
let instance: &PyAny = Py::new(py, SomeClass(0)).unwrap().into_ref(py);
|
|
|
|
let _: &PyCell<SomeClass> = PyTryInto::try_into(instance).unwrap();
|
|
|
|
let _: &PyCell<SomeClass> = PyTryInto::try_into_exact(instance).unwrap();
|
|
|
|
})
|
|
|
|
}
|
2022-06-12 07:51:47 +00:00
|
|
|
}
|
2019-02-23 17:01:22 +00:00
|
|
|
}
|