pyo3/
instance.rs

1use crate::err::{self, PyErr, PyResult};
2use crate::impl_::pycell::PyClassObject;
3use crate::internal_tricks::ptr_from_ref;
4use crate::pycell::{PyBorrowError, PyBorrowMutError};
5use crate::pyclass::boolean_struct::{False, True};
6#[cfg(feature = "gil-refs")]
7use crate::type_object::HasPyGilRef;
8use crate::types::{any::PyAnyMethods, string::PyStringMethods, typeobject::PyTypeMethods};
9use crate::types::{DerefToPyAny, PyDict, PyString, PyTuple};
10use crate::{
11    ffi, AsPyPointer, DowncastError, FromPyObject, IntoPy, PyAny, PyClass, PyClassInitializer,
12    PyRef, PyRefMut, PyTypeInfo, Python, ToPyObject,
13};
14use crate::{gil, PyTypeCheck};
15use std::marker::PhantomData;
16use std::mem::ManuallyDrop;
17use std::ops::Deref;
18use std::ptr::NonNull;
19
20/// Types that are built into the Python interpreter.
21///
22/// PyO3 is designed in a way that all references to those types are bound
23/// to the GIL, which is why you can get a token from all references of those
24/// types.
25///
26/// # Safety
27///
28/// This trait must only be implemented for types which cannot be accessed without the GIL.
29#[cfg(feature = "gil-refs")]
30pub unsafe trait PyNativeType: Sized {
31    /// The form of this which is stored inside a `Py<T>` smart pointer.
32    type AsRefSource: HasPyGilRef<AsRefTarget = Self>;
33
34    /// Cast `&self` to a `Borrowed` smart pointer.
35    ///
36    /// `Borrowed<T>` implements `Deref<Target=Bound<T>>`, so can also be used in locations
37    /// where `Bound<T>` is expected.
38    ///
39    /// This is available as a migration tool to adjust code from the deprecated "GIL Refs"
40    /// API to the `Bound` smart pointer API.
41    #[inline]
42    fn as_borrowed(&self) -> Borrowed<'_, '_, Self::AsRefSource> {
43        // Safety: &'py Self is expected to be a Python pointer,
44        // so has the same layout as Borrowed<'py, 'py, T>
45        Borrowed(
46            unsafe { NonNull::new_unchecked(ptr_from_ref(self) as *mut _) },
47            PhantomData,
48            self.py(),
49        )
50    }
51
52    /// Returns a GIL marker constrained to the lifetime of this type.
53    #[inline]
54    fn py(&self) -> Python<'_> {
55        unsafe { Python::assume_gil_acquired() }
56    }
57    /// Cast `&PyAny` to `&Self` without no type checking.
58    ///
59    /// # Safety
60    ///
61    /// `obj` must have the same layout as `*const ffi::PyObject` and must be
62    /// an instance of a type corresponding to `Self`.
63    unsafe fn unchecked_downcast(obj: &PyAny) -> &Self {
64        &*(obj.as_ptr() as *const Self)
65    }
66}
67
68/// A GIL-attached equivalent to [`Py<T>`].
69///
70/// This type can be thought of as equivalent to the tuple `(Py<T>, Python<'py>)`. By having the `'py`
71/// lifetime of the [`Python<'py>`] token, this ties the lifetime of the [`Bound<'py, T>`] smart pointer
72/// to the lifetime of the GIL and allows PyO3 to call Python APIs at maximum efficiency.
73///
74/// To access the object in situations where the GIL is not held, convert it to [`Py<T>`]
75/// using [`.unbind()`][Bound::unbind]. This includes situations where the GIL is temporarily
76/// released, such as [`Python::allow_threads`](crate::Python::allow_threads)'s closure.
77///
78/// See
79#[doc = concat!("[the guide](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/types.html#boundpy-t)")]
80/// for more detail.
81#[repr(transparent)]
82pub struct Bound<'py, T>(Python<'py>, ManuallyDrop<Py<T>>);
83
84impl<'py, T> Bound<'py, T>
85where
86    T: PyClass,
87{
88    /// Creates a new instance `Bound<T>` of a `#[pyclass]` on the Python heap.
89    ///
90    /// # Examples
91    ///
92    /// ```rust
93    /// use pyo3::prelude::*;
94    ///
95    /// #[pyclass]
96    /// struct Foo {/* fields omitted */}
97    ///
98    /// # fn main() -> PyResult<()> {
99    /// let foo: Py<Foo> = Python::with_gil(|py| -> PyResult<_> {
100    ///     let foo: Bound<'_, Foo> = Bound::new(py, Foo {})?;
101    ///     Ok(foo.into())
102    /// })?;
103    /// # Python::with_gil(move |_py| drop(foo));
104    /// # Ok(())
105    /// # }
106    /// ```
107    pub fn new(
108        py: Python<'py>,
109        value: impl Into<PyClassInitializer<T>>,
110    ) -> PyResult<Bound<'py, T>> {
111        value.into().create_class_object(py)
112    }
113}
114
115impl<'py> Bound<'py, PyAny> {
116    /// Constructs a new `Bound<'py, PyAny>` from a pointer. Panics if `ptr` is null.
117    ///
118    /// # Safety
119    ///
120    /// - `ptr` must be a valid pointer to a Python object
121    /// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership
122    #[inline]
123    #[track_caller]
124    pub unsafe fn from_owned_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
125        Self(py, ManuallyDrop::new(Py::from_owned_ptr(py, ptr)))
126    }
127
128    /// Constructs a new `Bound<'py, PyAny>` from a pointer. Returns `None` if `ptr` is null.
129    ///
130    /// # Safety
131    ///
132    /// - `ptr` must be a valid pointer to a Python object, or null
133    /// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership
134    #[inline]
135    pub unsafe fn from_owned_ptr_or_opt(py: Python<'py>, ptr: *mut ffi::PyObject) -> Option<Self> {
136        Py::from_owned_ptr_or_opt(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
137    }
138
139    /// Constructs a new `Bound<'py, PyAny>` from a pointer. Returns an `Err` by calling `PyErr::fetch`
140    /// if `ptr` is null.
141    ///
142    /// # Safety
143    ///
144    /// - `ptr` must be a valid pointer to a Python object, or null
145    /// - `ptr` must be an owned Python reference, as the `Bound<'py, PyAny>` will assume ownership
146    #[inline]
147    pub unsafe fn from_owned_ptr_or_err(
148        py: Python<'py>,
149        ptr: *mut ffi::PyObject,
150    ) -> PyResult<Self> {
151        Py::from_owned_ptr_or_err(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
152    }
153
154    /// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference.
155    /// Panics if `ptr` is null.
156    ///
157    /// # Safety
158    ///
159    /// - `ptr` must be a valid pointer to a Python object
160    #[inline]
161    #[track_caller]
162    pub unsafe fn from_borrowed_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
163        Self(py, ManuallyDrop::new(Py::from_borrowed_ptr(py, ptr)))
164    }
165
166    /// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference.
167    /// Returns `None` if `ptr` is null.
168    ///
169    /// # Safety
170    ///
171    /// - `ptr` must be a valid pointer to a Python object, or null
172    #[inline]
173    pub unsafe fn from_borrowed_ptr_or_opt(
174        py: Python<'py>,
175        ptr: *mut ffi::PyObject,
176    ) -> Option<Self> {
177        Py::from_borrowed_ptr_or_opt(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
178    }
179
180    /// Constructs a new `Bound<'py, PyAny>` from a pointer by creating a new Python reference.
181    /// Returns an `Err` by calling `PyErr::fetch` if `ptr` is null.
182    ///
183    /// # Safety
184    ///
185    /// - `ptr` must be a valid pointer to a Python object, or null
186    #[inline]
187    pub unsafe fn from_borrowed_ptr_or_err(
188        py: Python<'py>,
189        ptr: *mut ffi::PyObject,
190    ) -> PyResult<Self> {
191        Py::from_borrowed_ptr_or_err(py, ptr).map(|obj| Self(py, ManuallyDrop::new(obj)))
192    }
193
194    /// This slightly strange method is used to obtain `&Bound<PyAny>` from a pointer in macro code
195    /// where we need to constrain the lifetime `'a` safely.
196    ///
197    /// Note that `'py` is required to outlive `'a` implicitly by the nature of the fact that
198    /// `&'a Bound<'py>` means that `Bound<'py>` exists for at least the lifetime `'a`.
199    ///
200    /// # Safety
201    /// - `ptr` must be a valid pointer to a Python object for the lifetime `'a`. The `ptr` can
202    ///   be either a borrowed reference or an owned reference, it does not matter, as this is
203    ///   just `&Bound` there will never be any ownership transfer.
204    #[inline]
205    pub(crate) unsafe fn ref_from_ptr<'a>(
206        _py: Python<'py>,
207        ptr: &'a *mut ffi::PyObject,
208    ) -> &'a Self {
209        &*ptr_from_ref(ptr).cast::<Bound<'py, PyAny>>()
210    }
211
212    /// Variant of the above which returns `None` for null pointers.
213    ///
214    /// # Safety
215    /// - `ptr` must be a valid pointer to a Python object for the lifetime `'a, or null.
216    #[inline]
217    pub(crate) unsafe fn ref_from_ptr_or_opt<'a>(
218        _py: Python<'py>,
219        ptr: &'a *mut ffi::PyObject,
220    ) -> &'a Option<Self> {
221        &*ptr_from_ref(ptr).cast::<Option<Bound<'py, PyAny>>>()
222    }
223}
224
225impl<'py, T> Bound<'py, T>
226where
227    T: PyClass,
228{
229    /// Immutably borrows the value `T`.
230    ///
231    /// This borrow lasts while the returned [`PyRef`] exists.
232    /// Multiple immutable borrows can be taken out at the same time.
233    ///
234    /// For frozen classes, the simpler [`get`][Self::get] is available.
235    ///
236    /// # Examples
237    ///
238    /// ```rust
239    /// # use pyo3::prelude::*;
240    /// #
241    /// #[pyclass]
242    /// struct Foo {
243    ///     inner: u8,
244    /// }
245    ///
246    /// # fn main() -> PyResult<()> {
247    /// Python::with_gil(|py| -> PyResult<()> {
248    ///     let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
249    ///     let inner: &u8 = &foo.borrow().inner;
250    ///
251    ///     assert_eq!(*inner, 73);
252    ///     Ok(())
253    /// })?;
254    /// # Ok(())
255    /// # }
256    /// ```
257    ///
258    /// # Panics
259    ///
260    /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
261    /// [`try_borrow`](#method.try_borrow).
262    #[inline]
263    #[track_caller]
264    pub fn borrow(&self) -> PyRef<'py, T> {
265        PyRef::borrow(self)
266    }
267
268    /// Mutably borrows the value `T`.
269    ///
270    /// This borrow lasts while the returned [`PyRefMut`] exists.
271    ///
272    /// # Examples
273    ///
274    /// ```
275    /// # use pyo3::prelude::*;
276    /// #
277    /// #[pyclass]
278    /// struct Foo {
279    ///     inner: u8,
280    /// }
281    ///
282    /// # fn main() -> PyResult<()> {
283    /// Python::with_gil(|py| -> PyResult<()> {
284    ///     let foo: Bound<'_, Foo> = Bound::new(py, Foo { inner: 73 })?;
285    ///     foo.borrow_mut().inner = 35;
286    ///
287    ///     assert_eq!(foo.borrow().inner, 35);
288    ///     Ok(())
289    /// })?;
290    /// # Ok(())
291    /// # }
292    ///  ```
293    ///
294    /// # Panics
295    /// Panics if the value is currently borrowed. For a non-panicking variant, use
296    /// [`try_borrow_mut`](#method.try_borrow_mut).
297    #[inline]
298    #[track_caller]
299    pub fn borrow_mut(&self) -> PyRefMut<'py, T>
300    where
301        T: PyClass<Frozen = False>,
302    {
303        PyRefMut::borrow(self)
304    }
305
306    /// Attempts to immutably borrow the value `T`, returning an error if the value is currently mutably borrowed.
307    ///
308    /// The borrow lasts while the returned [`PyRef`] exists.
309    ///
310    /// This is the non-panicking variant of [`borrow`](#method.borrow).
311    ///
312    /// For frozen classes, the simpler [`get`][Self::get] is available.
313    #[inline]
314    pub fn try_borrow(&self) -> Result<PyRef<'py, T>, PyBorrowError> {
315        PyRef::try_borrow(self)
316    }
317
318    /// Attempts to mutably borrow the value `T`, returning an error if the value is currently borrowed.
319    ///
320    /// The borrow lasts while the returned [`PyRefMut`] exists.
321    ///
322    /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
323    #[inline]
324    pub fn try_borrow_mut(&self) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
325    where
326        T: PyClass<Frozen = False>,
327    {
328        PyRefMut::try_borrow(self)
329    }
330
331    /// Provide an immutable borrow of the value `T` without acquiring the GIL.
332    ///
333    /// This is available if the class is [`frozen`][macro@crate::pyclass] and [`Sync`].
334    ///
335    /// # Examples
336    ///
337    /// ```
338    /// use std::sync::atomic::{AtomicUsize, Ordering};
339    /// # use pyo3::prelude::*;
340    ///
341    /// #[pyclass(frozen)]
342    /// struct FrozenCounter {
343    ///     value: AtomicUsize,
344    /// }
345    ///
346    /// Python::with_gil(|py| {
347    ///     let counter = FrozenCounter { value: AtomicUsize::new(0) };
348    ///
349    ///     let py_counter = Bound::new(py, counter).unwrap();
350    ///
351    ///     py_counter.get().value.fetch_add(1, Ordering::Relaxed);
352    /// });
353    /// ```
354    #[inline]
355    pub fn get(&self) -> &T
356    where
357        T: PyClass<Frozen = True> + Sync,
358    {
359        self.1.get()
360    }
361
362    #[inline]
363    pub(crate) fn get_class_object(&self) -> &PyClassObject<T> {
364        self.1.get_class_object()
365    }
366}
367
368impl<'py, T> std::fmt::Debug for Bound<'py, T> {
369    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
370        let any = self.as_any();
371        python_format(any, any.repr(), f)
372    }
373}
374
375impl<'py, T> std::fmt::Display for Bound<'py, T> {
376    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
377        let any = self.as_any();
378        python_format(any, any.str(), f)
379    }
380}
381
382fn python_format(
383    any: &Bound<'_, PyAny>,
384    format_result: PyResult<Bound<'_, PyString>>,
385    f: &mut std::fmt::Formatter<'_>,
386) -> Result<(), std::fmt::Error> {
387    match format_result {
388        Result::Ok(s) => return f.write_str(&s.to_string_lossy()),
389        Result::Err(err) => err.write_unraisable_bound(any.py(), Some(any)),
390    }
391
392    match any.get_type().name() {
393        Result::Ok(name) => std::write!(f, "<unprintable {} object>", name),
394        Result::Err(_err) => f.write_str("<unprintable object>"),
395    }
396}
397
398// The trait bound is needed to avoid running into the auto-deref recursion
399// limit (error[E0055]), because `Bound<PyAny>` would deref into itself. See:
400// https://github.com/rust-lang/rust/issues/19509
401impl<'py, T> Deref for Bound<'py, T>
402where
403    T: DerefToPyAny,
404{
405    type Target = Bound<'py, PyAny>;
406
407    #[inline]
408    fn deref(&self) -> &Bound<'py, PyAny> {
409        self.as_any()
410    }
411}
412
413impl<'py, T> AsRef<Bound<'py, PyAny>> for Bound<'py, T> {
414    #[inline]
415    fn as_ref(&self) -> &Bound<'py, PyAny> {
416        self.as_any()
417    }
418}
419
420impl<T> Clone for Bound<'_, T> {
421    #[inline]
422    fn clone(&self) -> Self {
423        Self(self.0, ManuallyDrop::new(self.1.clone_ref(self.0)))
424    }
425}
426
427impl<T> Drop for Bound<'_, T> {
428    #[inline]
429    fn drop(&mut self) {
430        unsafe { ffi::Py_DECREF(self.as_ptr()) }
431    }
432}
433
434impl<'py, T> Bound<'py, T> {
435    /// Returns the GIL token associated with this object.
436    #[inline]
437    pub fn py(&self) -> Python<'py> {
438        self.0
439    }
440
441    /// Returns the raw FFI pointer represented by self.
442    ///
443    /// # Safety
444    ///
445    /// Callers are responsible for ensuring that the pointer does not outlive self.
446    ///
447    /// The reference is borrowed; callers should not decrease the reference count
448    /// when they are finished with the pointer.
449    #[inline]
450    pub fn as_ptr(&self) -> *mut ffi::PyObject {
451        self.1.as_ptr()
452    }
453
454    /// Returns an owned raw FFI pointer represented by self.
455    ///
456    /// # Safety
457    ///
458    /// The reference is owned; when finished the caller should either transfer ownership
459    /// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)).
460    #[inline]
461    pub fn into_ptr(self) -> *mut ffi::PyObject {
462        ManuallyDrop::new(self).as_ptr()
463    }
464
465    /// Helper to cast to `Bound<'py, PyAny>`.
466    #[inline]
467    pub fn as_any(&self) -> &Bound<'py, PyAny> {
468        // Safety: all Bound<T> have the same memory layout, and all Bound<T> are valid
469        // Bound<PyAny>, so pointer casting is valid.
470        unsafe { &*ptr_from_ref(self).cast::<Bound<'py, PyAny>>() }
471    }
472
473    /// Helper to cast to `Bound<'py, PyAny>`, transferring ownership.
474    #[inline]
475    pub fn into_any(self) -> Bound<'py, PyAny> {
476        // Safety: all Bound<T> are valid Bound<PyAny>
477        Bound(self.0, ManuallyDrop::new(self.unbind().into_any()))
478    }
479
480    /// Casts this `Bound<T>` to a `Borrowed<T>` smart pointer.
481    #[inline]
482    pub fn as_borrowed<'a>(&'a self) -> Borrowed<'a, 'py, T> {
483        Borrowed(
484            unsafe { NonNull::new_unchecked(self.as_ptr()) },
485            PhantomData,
486            self.py(),
487        )
488    }
489
490    /// Removes the connection for this `Bound<T>` from the GIL, allowing
491    /// it to cross thread boundaries.
492    #[inline]
493    pub fn unbind(self) -> Py<T> {
494        // Safety: the type T is known to be correct and the ownership of the
495        // pointer is transferred to the new Py<T> instance.
496        let non_null = (ManuallyDrop::new(self).1).0;
497        unsafe { Py::from_non_null(non_null) }
498    }
499
500    /// Removes the connection for this `Bound<T>` from the GIL, allowing
501    /// it to cross thread boundaries, without transferring ownership.
502    #[inline]
503    pub fn as_unbound(&self) -> &Py<T> {
504        &self.1
505    }
506
507    /// Casts this `Bound<T>` as the corresponding "GIL Ref" type.
508    ///
509    /// This is a helper to be used for migration from the deprecated "GIL Refs" API.
510    #[inline]
511    #[cfg(feature = "gil-refs")]
512    pub fn as_gil_ref(&'py self) -> &'py T::AsRefTarget
513    where
514        T: HasPyGilRef,
515    {
516        #[allow(deprecated)]
517        unsafe {
518            self.py().from_borrowed_ptr(self.as_ptr())
519        }
520    }
521
522    /// Casts this `Bound<T>` as the corresponding "GIL Ref" type, registering the pointer on the
523    /// [release pool](Python::from_owned_ptr).
524    ///
525    /// This is a helper to be used for migration from the deprecated "GIL Refs" API.
526    #[inline]
527    #[cfg(feature = "gil-refs")]
528    pub fn into_gil_ref(self) -> &'py T::AsRefTarget
529    where
530        T: HasPyGilRef,
531    {
532        #[allow(deprecated)]
533        unsafe {
534            self.py().from_owned_ptr(self.into_ptr())
535        }
536    }
537}
538
539unsafe impl<T> AsPyPointer for Bound<'_, T> {
540    #[inline]
541    fn as_ptr(&self) -> *mut ffi::PyObject {
542        self.1.as_ptr()
543    }
544}
545
546/// A borrowed equivalent to `Bound`.
547///
548/// The advantage of this over `&Bound` is that it avoids the need to have a pointer-to-pointer, as Bound
549/// is already a pointer to an `ffi::PyObject``.
550///
551/// Similarly, this type is `Copy` and `Clone`, like a shared reference (`&T`).
552#[repr(transparent)]
553pub struct Borrowed<'a, 'py, T>(NonNull<ffi::PyObject>, PhantomData<&'a Py<T>>, Python<'py>);
554
555impl<'py, T> Borrowed<'_, 'py, T> {
556    /// Creates a new owned [`Bound<T>`] from this borrowed reference by
557    /// increasing the reference count.
558    ///
559    /// # Example
560    /// ```
561    /// use pyo3::{prelude::*, types::PyTuple};
562    ///
563    /// # fn main() -> PyResult<()> {
564    /// Python::with_gil(|py| -> PyResult<()> {
565    ///     let tuple = PyTuple::new_bound(py, [1, 2, 3]);
566    ///
567    ///     // borrows from `tuple`, so can only be
568    ///     // used while `tuple` stays alive
569    ///     let borrowed = tuple.get_borrowed_item(0)?;
570    ///
571    ///     // creates a new owned reference, which
572    ///     // can be used indendently of `tuple`
573    ///     let bound = borrowed.to_owned();
574    ///     drop(tuple);
575    ///
576    ///     assert_eq!(bound.extract::<i32>().unwrap(), 1);
577    ///     Ok(())
578    /// })
579    /// # }
580    pub fn to_owned(self) -> Bound<'py, T> {
581        (*self).clone()
582    }
583}
584
585impl<'a, 'py> Borrowed<'a, 'py, PyAny> {
586    /// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Panics if `ptr` is null.
587    ///
588    /// Prefer to use [`Bound::from_borrowed_ptr`], as that avoids the major safety risk
589    /// of needing to precisely define the lifetime `'a` for which the borrow is valid.
590    ///
591    /// # Safety
592    ///
593    /// - `ptr` must be a valid pointer to a Python object
594    /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
595    ///   the caller and it is the caller's responsibility to ensure that the reference this is
596    ///   derived from is valid for the lifetime `'a`.
597    #[inline]
598    #[track_caller]
599    pub unsafe fn from_ptr(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
600        Self(
601            NonNull::new(ptr).unwrap_or_else(|| crate::err::panic_after_error(py)),
602            PhantomData,
603            py,
604        )
605    }
606
607    /// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Returns `None` if `ptr` is null.
608    ///
609    /// Prefer to use [`Bound::from_borrowed_ptr_or_opt`], as that avoids the major safety risk
610    /// of needing to precisely define the lifetime `'a` for which the borrow is valid.
611    ///
612    /// # Safety
613    ///
614    /// - `ptr` must be a valid pointer to a Python object, or null
615    /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
616    ///   the caller and it is the caller's responsibility to ensure that the reference this is
617    ///   derived from is valid for the lifetime `'a`.
618    #[inline]
619    pub unsafe fn from_ptr_or_opt(py: Python<'py>, ptr: *mut ffi::PyObject) -> Option<Self> {
620        NonNull::new(ptr).map(|ptr| Self(ptr, PhantomData, py))
621    }
622
623    /// Constructs a new `Borrowed<'a, 'py, PyAny>` from a pointer. Returns an `Err` by calling `PyErr::fetch`
624    /// if `ptr` is null.
625    ///
626    /// Prefer to use [`Bound::from_borrowed_ptr_or_err`], as that avoids the major safety risk
627    /// of needing to precisely define the lifetime `'a` for which the borrow is valid.
628    ///
629    /// # Safety
630    ///
631    /// - `ptr` must be a valid pointer to a Python object, or null
632    /// - similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
633    ///   the caller and it is the caller's responsibility to ensure that the reference this is
634    ///   derived from is valid for the lifetime `'a`.
635    #[inline]
636    pub unsafe fn from_ptr_or_err(py: Python<'py>, ptr: *mut ffi::PyObject) -> PyResult<Self> {
637        NonNull::new(ptr).map_or_else(
638            || Err(PyErr::fetch(py)),
639            |ptr| Ok(Self(ptr, PhantomData, py)),
640        )
641    }
642
643    /// # Safety
644    /// This is similar to `std::slice::from_raw_parts`, the lifetime `'a` is completely defined by
645    /// the caller and it's the caller's responsibility to ensure that the reference this is
646    /// derived from is valid for the lifetime `'a`.
647    #[inline]
648    pub(crate) unsafe fn from_ptr_unchecked(py: Python<'py>, ptr: *mut ffi::PyObject) -> Self {
649        Self(NonNull::new_unchecked(ptr), PhantomData, py)
650    }
651
652    #[inline]
653    #[cfg(not(feature = "gil-refs"))]
654    pub(crate) fn downcast<T>(self) -> Result<Borrowed<'a, 'py, T>, DowncastError<'a, 'py>>
655    where
656        T: PyTypeCheck,
657    {
658        if T::type_check(&self) {
659            // Safety: type_check is responsible for ensuring that the type is correct
660            Ok(unsafe { self.downcast_unchecked() })
661        } else {
662            Err(DowncastError::new_from_borrowed(self, T::NAME))
663        }
664    }
665
666    /// Converts this `PyAny` to a concrete Python type without checking validity.
667    ///
668    /// # Safety
669    /// Callers must ensure that the type is valid or risk type confusion.
670    #[inline]
671    pub(crate) unsafe fn downcast_unchecked<T>(self) -> Borrowed<'a, 'py, T> {
672        Borrowed(self.0, PhantomData, self.2)
673    }
674}
675
676impl<'a, 'py, T> From<&'a Bound<'py, T>> for Borrowed<'a, 'py, T> {
677    /// Create borrow on a Bound
678    #[inline]
679    fn from(instance: &'a Bound<'py, T>) -> Self {
680        instance.as_borrowed()
681    }
682}
683
684#[cfg(feature = "gil-refs")]
685impl<'py, T> Borrowed<'py, 'py, T>
686where
687    T: HasPyGilRef,
688{
689    pub(crate) fn into_gil_ref(self) -> &'py T::AsRefTarget {
690        // Safety: self is a borrow over `'py`.
691        #[allow(deprecated)]
692        unsafe {
693            self.py().from_borrowed_ptr(self.0.as_ptr())
694        }
695    }
696}
697
698impl<T> std::fmt::Debug for Borrowed<'_, '_, T> {
699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
700        Bound::fmt(self, f)
701    }
702}
703
704impl<'py, T> Deref for Borrowed<'_, 'py, T> {
705    type Target = Bound<'py, T>;
706
707    #[inline]
708    fn deref(&self) -> &Bound<'py, T> {
709        // safety: Bound has the same layout as NonNull<ffi::PyObject>
710        unsafe { &*ptr_from_ref(&self.0).cast() }
711    }
712}
713
714impl<T> Clone for Borrowed<'_, '_, T> {
715    #[inline]
716    fn clone(&self) -> Self {
717        *self
718    }
719}
720
721impl<T> Copy for Borrowed<'_, '_, T> {}
722
723impl<T> ToPyObject for Borrowed<'_, '_, T> {
724    /// Converts `Py` instance -> PyObject.
725    #[inline]
726    fn to_object(&self, py: Python<'_>) -> PyObject {
727        (*self).into_py(py)
728    }
729}
730
731impl<T> IntoPy<PyObject> for Borrowed<'_, '_, T> {
732    /// Converts `Py` instance -> PyObject.
733    #[inline]
734    fn into_py(self, py: Python<'_>) -> PyObject {
735        self.to_owned().into_py(py)
736    }
737}
738
739/// A GIL-independent reference to an object allocated on the Python heap.
740///
741/// This type does not auto-dereference to the inner object because you must prove you hold the GIL to access it.
742/// Instead, call one of its methods to access the inner object:
743///  - [`Py::bind`] or [`Py::into_bound`], to borrow a GIL-bound reference to the contained object.
744///  - [`Py::borrow`], [`Py::try_borrow`], [`Py::borrow_mut`], or [`Py::try_borrow_mut`],
745///
746/// to get a (mutable) reference to a contained pyclass, using a scheme similar to std's [`RefCell`].
747/// See the
748#[doc = concat!("[guide entry](https://pyo3.rs/v", env!("CARGO_PKG_VERSION"), "/class.html#bound-and-interior-mutability)")]
749/// for more information.
750///  - You can call methods directly on `Py` with [`Py::call_bound`], [`Py::call_method_bound`] and friends.
751///
752/// These require passing in the [`Python<'py>`](crate::Python) token but are otherwise similar to the corresponding
753/// methods on [`PyAny`].
754///
755/// # Example: Storing Python objects in `#[pyclass]` structs
756///
757/// Usually `Bound<'py, T>` is recommended for interacting with Python objects as its lifetime `'py`
758/// is an association to the GIL and that enables many operations to be done as efficiently as possible.
759///
760/// However, `#[pyclass]` structs cannot carry a lifetime, so `Py<T>` is the only way to store
761/// a Python object in a `#[pyclass]` struct.
762///
763/// For example, this won't compile:
764///
765/// ```compile_fail
766/// # use pyo3::prelude::*;
767/// # use pyo3::types::PyDict;
768/// #
769/// #[pyclass]
770/// struct Foo<'py> {
771///     inner: Bound<'py, PyDict>,
772/// }
773///
774/// impl Foo {
775///     fn new() -> Foo {
776///         let foo = Python::with_gil(|py| {
777///             // `py` will only last for this scope.
778///
779///             // `Bound<'py, PyDict>` inherits the GIL lifetime from `py` and
780///             // so won't be able to outlive this closure.
781///             let dict: Bound<'_, PyDict> = PyDict::new_bound(py);
782///
783///             // because `Foo` contains `dict` its lifetime
784///             // is now also tied to `py`.
785///             Foo { inner: dict }
786///         });
787///         // Foo is no longer valid.
788///         // Returning it from this function is a 💥 compiler error 💥
789///         foo
790///     }
791/// }
792/// ```
793///
794/// [`Py`]`<T>` can be used to get around this by converting `dict` into a GIL-independent reference:
795///
796/// ```rust
797/// use pyo3::prelude::*;
798/// use pyo3::types::PyDict;
799///
800/// #[pyclass]
801/// struct Foo {
802///     inner: Py<PyDict>,
803/// }
804///
805/// #[pymethods]
806/// impl Foo {
807///     #[new]
808///     fn __new__() -> Foo {
809///         Python::with_gil(|py| {
810///             let dict: Py<PyDict> = PyDict::new_bound(py).unbind();
811///             Foo { inner: dict }
812///         })
813///     }
814/// }
815/// #
816/// # fn main() -> PyResult<()> {
817/// #     Python::with_gil(|py| {
818/// #         let m = pyo3::types::PyModule::new_bound(py, "test")?;
819/// #         m.add_class::<Foo>()?;
820/// #
821/// #         let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?;
822/// #         let dict = &foo.borrow().inner;
823/// #         let dict: &Bound<'_, PyDict> = dict.bind(py);
824/// #
825/// #         Ok(())
826/// #     })
827/// # }
828/// ```
829///
830/// This can also be done with other pyclasses:
831/// ```rust
832/// use pyo3::prelude::*;
833///
834/// #[pyclass]
835/// struct Bar {/* ... */}
836///
837/// #[pyclass]
838/// struct Foo {
839///     inner: Py<Bar>,
840/// }
841///
842/// #[pymethods]
843/// impl Foo {
844///     #[new]
845///     fn __new__() -> PyResult<Foo> {
846///         Python::with_gil(|py| {
847///             let bar: Py<Bar> = Py::new(py, Bar {})?;
848///             Ok(Foo { inner: bar })
849///         })
850///     }
851/// }
852/// #
853/// # fn main() -> PyResult<()> {
854/// #     Python::with_gil(|py| {
855/// #         let m = pyo3::types::PyModule::new_bound(py, "test")?;
856/// #         m.add_class::<Foo>()?;
857/// #
858/// #         let foo: Bound<'_, Foo> = m.getattr("Foo")?.call0()?.downcast_into()?;
859/// #         let bar = &foo.borrow().inner;
860/// #         let bar: &Bar = &*bar.borrow(py);
861/// #
862/// #         Ok(())
863/// #     })
864/// # }
865/// ```
866///
867/// # Example: Shared ownership of Python objects
868///
869/// `Py<T>` can be used to share ownership of a Python object, similar to std's [`Rc`]`<T>`.
870/// As with [`Rc`]`<T>`, cloning it increases its reference count rather than duplicating
871/// the underlying object.
872///
873/// This can be done using either [`Py::clone_ref`] or [`Py`]`<T>`'s [`Clone`] trait implementation.
874/// [`Py::clone_ref`] will be faster if you happen to be already holding the GIL.
875///
876/// ```rust
877/// use pyo3::prelude::*;
878/// use pyo3::types::PyDict;
879///
880/// # fn main() {
881/// Python::with_gil(|py| {
882///     let first: Py<PyDict> = PyDict::new_bound(py).unbind();
883///
884///     // All of these are valid syntax
885///     let second = Py::clone_ref(&first, py);
886///     let third = first.clone_ref(py);
887///     #[cfg(feature = "py-clone")]
888///     let fourth = Py::clone(&first);
889///     #[cfg(feature = "py-clone")]
890///     let fifth = first.clone();
891///
892///     // Disposing of our original `Py<PyDict>` just decrements the reference count.
893///     drop(first);
894///
895///     // They all point to the same object
896///     assert!(second.is(&third));
897///     #[cfg(feature = "py-clone")]
898///     assert!(fourth.is(&fifth));
899///     #[cfg(feature = "py-clone")]
900///     assert!(second.is(&fourth));
901/// });
902/// # }
903/// ```
904///
905/// # Preventing reference cycles
906///
907/// It is easy to accidentally create reference cycles using [`Py`]`<T>`.
908/// The Python interpreter can break these reference cycles within pyclasses if they
909/// [integrate with the garbage collector][gc]. If your pyclass contains other Python
910/// objects you should implement it to avoid leaking memory.
911///
912/// # A note on Python reference counts
913///
914/// Dropping a [`Py`]`<T>` will eventually decrease Python's reference count
915/// of the pointed-to variable, allowing Python's garbage collector to free
916/// the associated memory, but this may not happen immediately.  This is
917/// because a [`Py`]`<T>` can be dropped at any time, but the Python reference
918/// count can only be modified when the GIL is held.
919///
920/// If a [`Py`]`<T>` is dropped while its thread happens to be holding the
921/// GIL then the Python reference count will be decreased immediately.
922/// Otherwise, the reference count will be decreased the next time the GIL is
923/// reacquired.
924///
925/// If you happen to be already holding the GIL, [`Py::drop_ref`] will decrease
926/// the Python reference count immediately and will execute slightly faster than
927/// relying on implicit [`Drop`]s.
928///
929/// # A note on `Send` and `Sync`
930///
931/// Accessing this object is threadsafe, since any access to its API requires a [`Python<'py>`](crate::Python) token.
932/// As you can only get this by acquiring the GIL, `Py<...>` implements [`Send`] and [`Sync`].
933///
934/// [`Rc`]: std::rc::Rc
935/// [`RefCell`]: std::cell::RefCell
936/// [gc]: https://pyo3.rs/main/class/protocols.html#garbage-collector-integration
937#[repr(transparent)]
938pub struct Py<T>(NonNull<ffi::PyObject>, PhantomData<T>);
939
940// The inner value is only accessed through ways that require proving the gil is held
941#[cfg(feature = "nightly")]
942unsafe impl<T> crate::marker::Ungil for Py<T> {}
943unsafe impl<T> Send for Py<T> {}
944unsafe impl<T> Sync for Py<T> {}
945
946impl<T> Py<T>
947where
948    T: PyClass,
949{
950    /// Creates a new instance `Py<T>` of a `#[pyclass]` on the Python heap.
951    ///
952    /// # Examples
953    ///
954    /// ```rust
955    /// use pyo3::prelude::*;
956    ///
957    /// #[pyclass]
958    /// struct Foo {/* fields omitted */}
959    ///
960    /// # fn main() -> PyResult<()> {
961    /// let foo = Python::with_gil(|py| -> PyResult<_> {
962    ///     let foo: Py<Foo> = Py::new(py, Foo {})?;
963    ///     Ok(foo)
964    /// })?;
965    /// # Python::with_gil(move |_py| drop(foo));
966    /// # Ok(())
967    /// # }
968    /// ```
969    pub fn new(py: Python<'_>, value: impl Into<PyClassInitializer<T>>) -> PyResult<Py<T>> {
970        Bound::new(py, value).map(Bound::unbind)
971    }
972}
973
974#[cfg(feature = "gil-refs")]
975impl<T> Py<T>
976where
977    T: HasPyGilRef,
978{
979    /// Borrows a GIL-bound reference to the contained `T`.
980    ///
981    /// By binding to the GIL lifetime, this allows the GIL-bound reference to not require
982    /// [`Python<'py>`](crate::Python) for any of its methods, which makes calling methods
983    /// on it more ergonomic.
984    ///
985    /// For native types, this reference is `&T`. For pyclasses, this is `&PyCell<T>`.
986    ///
987    /// Note that the lifetime of the returned reference is the shortest of `&self` and
988    /// [`Python<'py>`](crate::Python).
989    /// Consider using [`Py::into_ref`] instead if this poses a problem.
990    ///
991    /// # Examples
992    ///
993    /// Get access to `&PyList` from `Py<PyList>`:
994    ///
995    /// ```
996    /// # use pyo3::prelude::*;
997    /// # use pyo3::types::PyList;
998    /// #
999    /// Python::with_gil(|py| {
1000    ///     let list: Py<PyList> = PyList::empty_bound(py).into();
1001    ///     # #[allow(deprecated)]
1002    ///     let list: &PyList = list.as_ref(py);
1003    ///     assert_eq!(list.len(), 0);
1004    /// });
1005    /// ```
1006    ///
1007    /// Get access to `&PyCell<MyClass>` from `Py<MyClass>`:
1008    ///
1009    /// ```
1010    /// # use pyo3::prelude::*;
1011    /// #
1012    /// #[pyclass]
1013    /// struct MyClass {}
1014    ///
1015    /// Python::with_gil(|py| {
1016    ///     let my_class: Py<MyClass> = Py::new(py, MyClass {}).unwrap();
1017    ///     # #[allow(deprecated)]
1018    ///     let my_class_cell: &PyCell<MyClass> = my_class.as_ref(py);
1019    ///     assert!(my_class_cell.try_borrow().is_ok());
1020    /// });
1021    /// ```
1022    #[deprecated(
1023        since = "0.21.0",
1024        note = "use `obj.bind(py)` instead of `obj.as_ref(py)`"
1025    )]
1026    pub fn as_ref<'py>(&'py self, _py: Python<'py>) -> &'py T::AsRefTarget {
1027        let any = self.as_ptr() as *const PyAny;
1028        unsafe { PyNativeType::unchecked_downcast(&*any) }
1029    }
1030
1031    /// Borrows a GIL-bound reference to the contained `T` independently of the lifetime of `T`.
1032    ///
1033    /// This method is similar to [`as_ref`](#method.as_ref) but consumes `self` and registers the
1034    /// Python object reference in PyO3's object storage. The reference count for the Python
1035    /// object will not be decreased until the GIL lifetime ends.
1036    ///
1037    /// You should prefer using [`as_ref`](#method.as_ref) if you can as it'll have less overhead.
1038    ///
1039    /// # Examples
1040    ///
1041    /// [`Py::as_ref`]'s lifetime limitation forbids creating a function that references a
1042    /// variable created inside the function.
1043    ///
1044    /// ```rust,compile_fail
1045    /// # use pyo3::prelude::*;
1046    /// #
1047    /// fn new_py_any<'py>(py: Python<'py>, value: impl IntoPy<Py<PyAny>>) -> &'py PyAny {
1048    ///     let obj: Py<PyAny> = value.into_py(py);
1049    ///
1050    ///     // The lifetime of the return value of this function is the shortest
1051    ///     // of `obj` and `py`. As `obj` is owned by the current function,
1052    ///     // Rust won't let the return value escape this function!
1053    ///     obj.as_ref(py)
1054    /// }
1055    /// ```
1056    ///
1057    /// This can be solved by using [`Py::into_ref`] instead, which does not suffer from this issue.
1058    /// Note that the lifetime of the [`Python<'py>`](crate::Python) token is transferred to
1059    /// the returned reference.
1060    ///
1061    /// ```rust
1062    /// # use pyo3::prelude::*;
1063    /// # #[allow(dead_code)] // This is just to show it compiles.
1064    /// fn new_py_any<'py>(py: Python<'py>, value: impl IntoPy<Py<PyAny>>) -> &'py PyAny {
1065    ///     let obj: Py<PyAny> = value.into_py(py);
1066    ///
1067    ///     // This reference's lifetime is determined by `py`'s lifetime.
1068    ///     // Because that originates from outside this function,
1069    ///     // this return value is allowed.
1070    ///     # #[allow(deprecated)]
1071    ///     obj.into_ref(py)
1072    /// }
1073    /// ```
1074    #[deprecated(
1075        since = "0.21.0",
1076        note = "use `obj.into_bound(py)` instead of `obj.into_ref(py)`"
1077    )]
1078    pub fn into_ref(self, py: Python<'_>) -> &T::AsRefTarget {
1079        #[allow(deprecated)]
1080        unsafe {
1081            py.from_owned_ptr(self.into_ptr())
1082        }
1083    }
1084}
1085
1086impl<T> Py<T> {
1087    /// Returns the raw FFI pointer represented by self.
1088    ///
1089    /// # Safety
1090    ///
1091    /// Callers are responsible for ensuring that the pointer does not outlive self.
1092    ///
1093    /// The reference is borrowed; callers should not decrease the reference count
1094    /// when they are finished with the pointer.
1095    #[inline]
1096    pub fn as_ptr(&self) -> *mut ffi::PyObject {
1097        self.0.as_ptr()
1098    }
1099
1100    /// Returns an owned raw FFI pointer represented by self.
1101    ///
1102    /// # Safety
1103    ///
1104    /// The reference is owned; when finished the caller should either transfer ownership
1105    /// of the pointer or decrease the reference count (e.g. with [`pyo3::ffi::Py_DecRef`](crate::ffi::Py_DecRef)).
1106    #[inline]
1107    pub fn into_ptr(self) -> *mut ffi::PyObject {
1108        ManuallyDrop::new(self).0.as_ptr()
1109    }
1110
1111    /// Helper to cast to `Py<PyAny>`.
1112    #[inline]
1113    pub fn as_any(&self) -> &Py<PyAny> {
1114        // Safety: all Py<T> have the same memory layout, and all Py<T> are valid
1115        // Py<PyAny>, so pointer casting is valid.
1116        unsafe { &*ptr_from_ref(self).cast::<Py<PyAny>>() }
1117    }
1118
1119    /// Helper to cast to `Py<PyAny>`, transferring ownership.
1120    #[inline]
1121    pub fn into_any(self) -> Py<PyAny> {
1122        // Safety: all Py<T> are valid Py<PyAny>
1123        unsafe { Py::from_non_null(ManuallyDrop::new(self).0) }
1124    }
1125}
1126
1127impl<T> Py<T>
1128where
1129    T: PyClass,
1130{
1131    /// Immutably borrows the value `T`.
1132    ///
1133    /// This borrow lasts while the returned [`PyRef`] exists.
1134    /// Multiple immutable borrows can be taken out at the same time.
1135    ///
1136    /// For frozen classes, the simpler [`get`][Self::get] is available.
1137    ///
1138    /// Equivalent to `self.bind(py).borrow()` - see [`Bound::borrow`].
1139    ///
1140    /// # Examples
1141    ///
1142    /// ```rust
1143    /// # use pyo3::prelude::*;
1144    /// #
1145    /// #[pyclass]
1146    /// struct Foo {
1147    ///     inner: u8,
1148    /// }
1149    ///
1150    /// # fn main() -> PyResult<()> {
1151    /// Python::with_gil(|py| -> PyResult<()> {
1152    ///     let foo: Py<Foo> = Py::new(py, Foo { inner: 73 })?;
1153    ///     let inner: &u8 = &foo.borrow(py).inner;
1154    ///
1155    ///     assert_eq!(*inner, 73);
1156    ///     Ok(())
1157    /// })?;
1158    /// # Ok(())
1159    /// # }
1160    /// ```
1161    ///
1162    /// # Panics
1163    ///
1164    /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
1165    /// [`try_borrow`](#method.try_borrow).
1166    #[inline]
1167    #[track_caller]
1168    pub fn borrow<'py>(&'py self, py: Python<'py>) -> PyRef<'py, T> {
1169        self.bind(py).borrow()
1170    }
1171
1172    /// Mutably borrows the value `T`.
1173    ///
1174    /// This borrow lasts while the returned [`PyRefMut`] exists.
1175    ///
1176    /// Equivalent to `self.bind(py).borrow_mut()` - see [`Bound::borrow_mut`].
1177    ///
1178    /// # Examples
1179    ///
1180    /// ```
1181    /// # use pyo3::prelude::*;
1182    /// #
1183    /// #[pyclass]
1184    /// struct Foo {
1185    ///     inner: u8,
1186    /// }
1187    ///
1188    /// # fn main() -> PyResult<()> {
1189    /// Python::with_gil(|py| -> PyResult<()> {
1190    ///     let foo: Py<Foo> = Py::new(py, Foo { inner: 73 })?;
1191    ///     foo.borrow_mut(py).inner = 35;
1192    ///
1193    ///     assert_eq!(foo.borrow(py).inner, 35);
1194    ///     Ok(())
1195    /// })?;
1196    /// # Ok(())
1197    /// # }
1198    ///  ```
1199    ///
1200    /// # Panics
1201    /// Panics if the value is currently borrowed. For a non-panicking variant, use
1202    /// [`try_borrow_mut`](#method.try_borrow_mut).
1203    #[inline]
1204    #[track_caller]
1205    pub fn borrow_mut<'py>(&'py self, py: Python<'py>) -> PyRefMut<'py, T>
1206    where
1207        T: PyClass<Frozen = False>,
1208    {
1209        self.bind(py).borrow_mut()
1210    }
1211
1212    /// Attempts to immutably borrow the value `T`, returning an error if the value is currently mutably borrowed.
1213    ///
1214    /// The borrow lasts while the returned [`PyRef`] exists.
1215    ///
1216    /// This is the non-panicking variant of [`borrow`](#method.borrow).
1217    ///
1218    /// For frozen classes, the simpler [`get`][Self::get] is available.
1219    ///
1220    /// Equivalent to `self.bind(py).try_borrow()` - see [`Bound::try_borrow`].
1221    #[inline]
1222    pub fn try_borrow<'py>(&'py self, py: Python<'py>) -> Result<PyRef<'py, T>, PyBorrowError> {
1223        self.bind(py).try_borrow()
1224    }
1225
1226    /// Attempts to mutably borrow the value `T`, returning an error if the value is currently borrowed.
1227    ///
1228    /// The borrow lasts while the returned [`PyRefMut`] exists.
1229    ///
1230    /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
1231    ///
1232    /// Equivalent to `self.bind(py).try_borrow_mut()` - see [`Bound::try_borrow_mut`].
1233    #[inline]
1234    pub fn try_borrow_mut<'py>(
1235        &'py self,
1236        py: Python<'py>,
1237    ) -> Result<PyRefMut<'py, T>, PyBorrowMutError>
1238    where
1239        T: PyClass<Frozen = False>,
1240    {
1241        self.bind(py).try_borrow_mut()
1242    }
1243
1244    /// Provide an immutable borrow of the value `T` without acquiring the GIL.
1245    ///
1246    /// This is available if the class is [`frozen`][macro@crate::pyclass] and [`Sync`].
1247    ///
1248    /// # Examples
1249    ///
1250    /// ```
1251    /// use std::sync::atomic::{AtomicUsize, Ordering};
1252    /// # use pyo3::prelude::*;
1253    ///
1254    /// #[pyclass(frozen)]
1255    /// struct FrozenCounter {
1256    ///     value: AtomicUsize,
1257    /// }
1258    ///
1259    /// let cell  = Python::with_gil(|py| {
1260    ///     let counter = FrozenCounter { value: AtomicUsize::new(0) };
1261    ///
1262    ///     Py::new(py, counter).unwrap()
1263    /// });
1264    ///
1265    /// cell.get().value.fetch_add(1, Ordering::Relaxed);
1266    /// # Python::with_gil(move |_py| drop(cell));
1267    /// ```
1268    #[inline]
1269    pub fn get(&self) -> &T
1270    where
1271        T: PyClass<Frozen = True> + Sync,
1272    {
1273        // Safety: The class itself is frozen and `Sync`
1274        unsafe { &*self.get_class_object().get_ptr() }
1275    }
1276
1277    /// Get a view on the underlying `PyClass` contents.
1278    #[inline]
1279    pub(crate) fn get_class_object(&self) -> &PyClassObject<T> {
1280        let class_object = self.as_ptr().cast::<PyClassObject<T>>();
1281        // Safety: Bound<T: PyClass> is known to contain an object which is laid out in memory as a
1282        // PyClassObject<T>.
1283        unsafe { &*class_object }
1284    }
1285}
1286
1287impl<T> Py<T> {
1288    /// Attaches this `Py` to the given Python context, allowing access to further Python APIs.
1289    #[inline]
1290    pub fn bind<'py>(&self, _py: Python<'py>) -> &Bound<'py, T> {
1291        // Safety: `Bound` has the same layout as `Py`
1292        unsafe { &*ptr_from_ref(self).cast() }
1293    }
1294
1295    /// Same as `bind` but takes ownership of `self`.
1296    #[inline]
1297    pub fn into_bound(self, py: Python<'_>) -> Bound<'_, T> {
1298        Bound(py, ManuallyDrop::new(self))
1299    }
1300
1301    /// Same as `bind` but produces a `Borrowed<T>` instead of a `Bound<T>`.
1302    #[inline]
1303    pub fn bind_borrowed<'a, 'py>(&'a self, py: Python<'py>) -> Borrowed<'a, 'py, T> {
1304        Borrowed(self.0, PhantomData, py)
1305    }
1306
1307    /// Returns whether `self` and `other` point to the same object. To compare
1308    /// the equality of two objects (the `==` operator), use [`eq`](PyAnyMethods::eq).
1309    ///
1310    /// This is equivalent to the Python expression `self is other`.
1311    #[inline]
1312    pub fn is<U: AsPyPointer>(&self, o: &U) -> bool {
1313        self.as_ptr() == o.as_ptr()
1314    }
1315
1316    /// Gets the reference count of the `ffi::PyObject` pointer.
1317    #[inline]
1318    pub fn get_refcnt(&self, _py: Python<'_>) -> isize {
1319        unsafe { ffi::Py_REFCNT(self.0.as_ptr()) }
1320    }
1321
1322    /// Makes a clone of `self`.
1323    ///
1324    /// This creates another pointer to the same object, increasing its reference count.
1325    ///
1326    /// You should prefer using this method over [`Clone`] if you happen to be holding the GIL already.
1327    ///
1328    /// # Examples
1329    ///
1330    /// ```rust
1331    /// use pyo3::prelude::*;
1332    /// use pyo3::types::PyDict;
1333    ///
1334    /// # fn main() {
1335    /// Python::with_gil(|py| {
1336    ///     let first: Py<PyDict> = PyDict::new_bound(py).unbind();
1337    ///     let second = Py::clone_ref(&first, py);
1338    ///
1339    ///     // Both point to the same object
1340    ///     assert!(first.is(&second));
1341    /// });
1342    /// # }
1343    /// ```
1344    #[inline]
1345    pub fn clone_ref(&self, _py: Python<'_>) -> Py<T> {
1346        unsafe {
1347            ffi::Py_INCREF(self.as_ptr());
1348            Self::from_non_null(self.0)
1349        }
1350    }
1351
1352    /// Drops `self` and immediately decreases its reference count.
1353    ///
1354    /// This method is a micro-optimisation over [`Drop`] if you happen to be holding the GIL
1355    /// already.
1356    ///
1357    /// Note that if you are using [`Bound`], you do not need to use [`Self::drop_ref`] since
1358    /// [`Bound`] guarantees that the GIL is held.
1359    ///
1360    /// # Examples
1361    ///
1362    /// ```rust
1363    /// use pyo3::prelude::*;
1364    /// use pyo3::types::PyDict;
1365    ///
1366    /// # fn main() {
1367    /// Python::with_gil(|py| {
1368    ///     let object: Py<PyDict> = PyDict::new_bound(py).unbind();
1369    ///
1370    ///     // some usage of object
1371    ///
1372    ///     object.drop_ref(py);
1373    /// });
1374    /// # }
1375    /// ```
1376    #[inline]
1377    pub fn drop_ref(self, py: Python<'_>) {
1378        let _ = self.into_bound(py);
1379    }
1380
1381    /// Returns whether the object is considered to be None.
1382    ///
1383    /// This is equivalent to the Python expression `self is None`.
1384    pub fn is_none(&self, _py: Python<'_>) -> bool {
1385        unsafe { ffi::Py_None() == self.as_ptr() }
1386    }
1387
1388    /// Returns whether the object is Ellipsis, e.g. `...`.
1389    ///
1390    /// This is equivalent to the Python expression `self is ...`.
1391    #[deprecated(since = "0.20.0", note = "use `.is(py.Ellipsis())` instead")]
1392    pub fn is_ellipsis(&self) -> bool {
1393        unsafe { ffi::Py_Ellipsis() == self.as_ptr() }
1394    }
1395
1396    /// Returns whether the object is considered to be true.
1397    ///
1398    /// This is equivalent to the Python expression `bool(self)`.
1399    #[deprecated(since = "0.21.0", note = "use `.is_truthy()` instead")]
1400    pub fn is_true(&self, py: Python<'_>) -> PyResult<bool> {
1401        self.is_truthy(py)
1402    }
1403
1404    /// Returns whether the object is considered to be true.
1405    ///
1406    /// This applies truth value testing equivalent to the Python expression `bool(self)`.
1407    pub fn is_truthy(&self, py: Python<'_>) -> PyResult<bool> {
1408        let v = unsafe { ffi::PyObject_IsTrue(self.as_ptr()) };
1409        err::error_on_minusone(py, v)?;
1410        Ok(v != 0)
1411    }
1412
1413    /// Extracts some type from the Python object.
1414    ///
1415    /// This is a wrapper function around `FromPyObject::extract()`.
1416    pub fn extract<'a, 'py, D>(&'a self, py: Python<'py>) -> PyResult<D>
1417    where
1418        D: crate::conversion::FromPyObjectBound<'a, 'py>,
1419        // TODO it might be possible to relax this bound in future, to allow
1420        // e.g. `.extract::<&str>(py)` where `py` is short-lived.
1421        'py: 'a,
1422    {
1423        self.bind(py).as_any().extract()
1424    }
1425
1426    /// Retrieves an attribute value.
1427    ///
1428    /// This is equivalent to the Python expression `self.attr_name`.
1429    ///
1430    /// If calling this method becomes performance-critical, the [`intern!`](crate::intern) macro
1431    /// can be used to intern `attr_name`, thereby avoiding repeated temporary allocations of
1432    /// Python strings.
1433    ///
1434    /// # Example: `intern!`ing the attribute name
1435    ///
1436    /// ```
1437    /// # use pyo3::{prelude::*, intern};
1438    /// #
1439    /// #[pyfunction]
1440    /// fn version(sys: Py<PyModule>, py: Python<'_>) -> PyResult<PyObject> {
1441    ///     sys.getattr(py, intern!(py, "version"))
1442    /// }
1443    /// #
1444    /// # Python::with_gil(|py| {
1445    /// #    let sys = py.import_bound("sys").unwrap().unbind();
1446    /// #    version(sys, py).unwrap();
1447    /// # });
1448    /// ```
1449    pub fn getattr<N>(&self, py: Python<'_>, attr_name: N) -> PyResult<PyObject>
1450    where
1451        N: IntoPy<Py<PyString>>,
1452    {
1453        self.bind(py).as_any().getattr(attr_name).map(Bound::unbind)
1454    }
1455
1456    /// Sets an attribute value.
1457    ///
1458    /// This is equivalent to the Python expression `self.attr_name = value`.
1459    ///
1460    /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
1461    /// macro can be used to intern `attr_name`.
1462    ///
1463    /// # Example: `intern!`ing the attribute name
1464    ///
1465    /// ```
1466    /// # use pyo3::{intern, pyfunction, types::PyModule, IntoPy, PyObject, Python, PyResult};
1467    /// #
1468    /// #[pyfunction]
1469    /// fn set_answer(ob: PyObject, py: Python<'_>) -> PyResult<()> {
1470    ///     ob.setattr(py, intern!(py, "answer"), 42)
1471    /// }
1472    /// #
1473    /// # Python::with_gil(|py| {
1474    /// #    let ob = PyModule::new_bound(py, "empty").unwrap().into_py(py);
1475    /// #    set_answer(ob, py).unwrap();
1476    /// # });
1477    /// ```
1478    pub fn setattr<N, V>(&self, py: Python<'_>, attr_name: N, value: V) -> PyResult<()>
1479    where
1480        N: IntoPy<Py<PyString>>,
1481        V: IntoPy<Py<PyAny>>,
1482    {
1483        self.bind(py)
1484            .as_any()
1485            .setattr(attr_name, value.into_py(py).into_bound(py))
1486    }
1487
1488    /// Deprecated form of [`call_bound`][Py::call_bound].
1489    #[cfg(feature = "gil-refs")]
1490    #[deprecated(
1491        since = "0.21.0",
1492        note = "`call` will be replaced by `call_bound` in a future PyO3 version"
1493    )]
1494    #[inline]
1495    pub fn call<A>(&self, py: Python<'_>, args: A, kwargs: Option<&PyDict>) -> PyResult<PyObject>
1496    where
1497        A: IntoPy<Py<PyTuple>>,
1498    {
1499        self.call_bound(py, args, kwargs.map(PyDict::as_borrowed).as_deref())
1500    }
1501
1502    /// Calls the object.
1503    ///
1504    /// This is equivalent to the Python expression `self(*args, **kwargs)`.
1505    pub fn call_bound<N>(
1506        &self,
1507        py: Python<'_>,
1508        args: N,
1509        kwargs: Option<&Bound<'_, PyDict>>,
1510    ) -> PyResult<PyObject>
1511    where
1512        N: IntoPy<Py<PyTuple>>,
1513    {
1514        self.bind(py).as_any().call(args, kwargs).map(Bound::unbind)
1515    }
1516
1517    /// Calls the object with only positional arguments.
1518    ///
1519    /// This is equivalent to the Python expression `self(*args)`.
1520    pub fn call1<N>(&self, py: Python<'_>, args: N) -> PyResult<PyObject>
1521    where
1522        N: IntoPy<Py<PyTuple>>,
1523    {
1524        self.bind(py).as_any().call1(args).map(Bound::unbind)
1525    }
1526
1527    /// Calls the object without arguments.
1528    ///
1529    /// This is equivalent to the Python expression `self()`.
1530    pub fn call0(&self, py: Python<'_>) -> PyResult<PyObject> {
1531        self.bind(py).as_any().call0().map(Bound::unbind)
1532    }
1533
1534    /// Deprecated form of [`call_method_bound`][Py::call_method_bound].
1535    #[cfg(feature = "gil-refs")]
1536    #[deprecated(
1537        since = "0.21.0",
1538        note = "`call_method` will be replaced by `call_method_bound` in a future PyO3 version"
1539    )]
1540    #[inline]
1541    pub fn call_method<N, A>(
1542        &self,
1543        py: Python<'_>,
1544        name: N,
1545        args: A,
1546        kwargs: Option<&PyDict>,
1547    ) -> PyResult<PyObject>
1548    where
1549        N: IntoPy<Py<PyString>>,
1550        A: IntoPy<Py<PyTuple>>,
1551    {
1552        self.call_method_bound(py, name, args, kwargs.map(PyDict::as_borrowed).as_deref())
1553    }
1554
1555    /// Calls a method on the object.
1556    ///
1557    /// This is equivalent to the Python expression `self.name(*args, **kwargs)`.
1558    ///
1559    /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
1560    /// macro can be used to intern `name`.
1561    pub fn call_method_bound<N, A>(
1562        &self,
1563        py: Python<'_>,
1564        name: N,
1565        args: A,
1566        kwargs: Option<&Bound<'_, PyDict>>,
1567    ) -> PyResult<PyObject>
1568    where
1569        N: IntoPy<Py<PyString>>,
1570        A: IntoPy<Py<PyTuple>>,
1571    {
1572        self.bind(py)
1573            .as_any()
1574            .call_method(name, args, kwargs)
1575            .map(Bound::unbind)
1576    }
1577
1578    /// Calls a method on the object with only positional arguments.
1579    ///
1580    /// This is equivalent to the Python expression `self.name(*args)`.
1581    ///
1582    /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
1583    /// macro can be used to intern `name`.
1584    pub fn call_method1<N, A>(&self, py: Python<'_>, name: N, args: A) -> PyResult<PyObject>
1585    where
1586        N: IntoPy<Py<PyString>>,
1587        A: IntoPy<Py<PyTuple>>,
1588    {
1589        self.bind(py)
1590            .as_any()
1591            .call_method1(name, args)
1592            .map(Bound::unbind)
1593    }
1594
1595    /// Calls a method on the object with no arguments.
1596    ///
1597    /// This is equivalent to the Python expression `self.name()`.
1598    ///
1599    /// To avoid repeated temporary allocations of Python strings, the [`intern!`](crate::intern)
1600    /// macro can be used to intern `name`.
1601    pub fn call_method0<N>(&self, py: Python<'_>, name: N) -> PyResult<PyObject>
1602    where
1603        N: IntoPy<Py<PyString>>,
1604    {
1605        self.bind(py).as_any().call_method0(name).map(Bound::unbind)
1606    }
1607
1608    /// Create a `Py<T>` instance by taking ownership of the given FFI pointer.
1609    ///
1610    /// # Safety
1611    /// `ptr` must be a pointer to a Python object of type T.
1612    ///
1613    /// Callers must own the object referred to by `ptr`, as this function
1614    /// implicitly takes ownership of that object.
1615    ///
1616    /// # Panics
1617    /// Panics if `ptr` is null.
1618    #[inline]
1619    #[track_caller]
1620    pub unsafe fn from_owned_ptr(py: Python<'_>, ptr: *mut ffi::PyObject) -> Py<T> {
1621        match NonNull::new(ptr) {
1622            Some(nonnull_ptr) => Py(nonnull_ptr, PhantomData),
1623            None => crate::err::panic_after_error(py),
1624        }
1625    }
1626
1627    /// Create a `Py<T>` instance by taking ownership of the given FFI pointer.
1628    ///
1629    /// If `ptr` is null then the current Python exception is fetched as a [`PyErr`].
1630    ///
1631    /// # Safety
1632    /// If non-null, `ptr` must be a pointer to a Python object of type T.
1633    #[inline]
1634    pub unsafe fn from_owned_ptr_or_err(
1635        py: Python<'_>,
1636        ptr: *mut ffi::PyObject,
1637    ) -> PyResult<Py<T>> {
1638        match NonNull::new(ptr) {
1639            Some(nonnull_ptr) => Ok(Py(nonnull_ptr, PhantomData)),
1640            None => Err(PyErr::fetch(py)),
1641        }
1642    }
1643
1644    /// Create a `Py<T>` instance by taking ownership of the given FFI pointer.
1645    ///
1646    /// If `ptr` is null then `None` is returned.
1647    ///
1648    /// # Safety
1649    /// If non-null, `ptr` must be a pointer to a Python object of type T.
1650    #[inline]
1651    pub unsafe fn from_owned_ptr_or_opt(_py: Python<'_>, ptr: *mut ffi::PyObject) -> Option<Self> {
1652        NonNull::new(ptr).map(|nonnull_ptr| Py(nonnull_ptr, PhantomData))
1653    }
1654
1655    /// Create a `Py<T>` instance by creating a new reference from the given FFI pointer.
1656    ///
1657    /// # Safety
1658    /// `ptr` must be a pointer to a Python object of type T.
1659    ///
1660    /// # Panics
1661    /// Panics if `ptr` is null.
1662    #[inline]
1663    #[track_caller]
1664    pub unsafe fn from_borrowed_ptr(py: Python<'_>, ptr: *mut ffi::PyObject) -> Py<T> {
1665        match Self::from_borrowed_ptr_or_opt(py, ptr) {
1666            Some(slf) => slf,
1667            None => crate::err::panic_after_error(py),
1668        }
1669    }
1670
1671    /// Create a `Py<T>` instance by creating a new reference from the given FFI pointer.
1672    ///
1673    /// If `ptr` is null then the current Python exception is fetched as a `PyErr`.
1674    ///
1675    /// # Safety
1676    /// `ptr` must be a pointer to a Python object of type T.
1677    #[inline]
1678    pub unsafe fn from_borrowed_ptr_or_err(
1679        py: Python<'_>,
1680        ptr: *mut ffi::PyObject,
1681    ) -> PyResult<Self> {
1682        Self::from_borrowed_ptr_or_opt(py, ptr).ok_or_else(|| PyErr::fetch(py))
1683    }
1684
1685    /// Create a `Py<T>` instance by creating a new reference from the given FFI pointer.
1686    ///
1687    /// If `ptr` is null then `None` is returned.
1688    ///
1689    /// # Safety
1690    /// `ptr` must be a pointer to a Python object of type T.
1691    #[inline]
1692    pub unsafe fn from_borrowed_ptr_or_opt(
1693        _py: Python<'_>,
1694        ptr: *mut ffi::PyObject,
1695    ) -> Option<Self> {
1696        NonNull::new(ptr).map(|nonnull_ptr| {
1697            ffi::Py_INCREF(ptr);
1698            Py(nonnull_ptr, PhantomData)
1699        })
1700    }
1701
1702    /// For internal conversions.
1703    ///
1704    /// # Safety
1705    /// `ptr` must point to a Python object of type T.
1706    unsafe fn from_non_null(ptr: NonNull<ffi::PyObject>) -> Self {
1707        Self(ptr, PhantomData)
1708    }
1709}
1710
1711impl<T> ToPyObject for Py<T> {
1712    /// Converts `Py` instance -> PyObject.
1713    #[inline]
1714    fn to_object(&self, py: Python<'_>) -> PyObject {
1715        self.clone_ref(py).into_any()
1716    }
1717}
1718
1719impl<T> IntoPy<PyObject> for Py<T> {
1720    /// Converts a `Py` instance to `PyObject`.
1721    /// Consumes `self` without calling `Py_DECREF()`.
1722    #[inline]
1723    fn into_py(self, _py: Python<'_>) -> PyObject {
1724        self.into_any()
1725    }
1726}
1727
1728impl<T> IntoPy<PyObject> for &'_ Py<T> {
1729    #[inline]
1730    fn into_py(self, py: Python<'_>) -> PyObject {
1731        self.to_object(py)
1732    }
1733}
1734
1735impl<T> ToPyObject for Bound<'_, T> {
1736    /// Converts `&Bound` instance -> PyObject, increasing the reference count.
1737    #[inline]
1738    fn to_object(&self, py: Python<'_>) -> PyObject {
1739        self.clone().into_py(py)
1740    }
1741}
1742
1743impl<T> IntoPy<PyObject> for Bound<'_, T> {
1744    /// Converts a `Bound` instance to `PyObject`.
1745    #[inline]
1746    fn into_py(self, _py: Python<'_>) -> PyObject {
1747        self.into_any().unbind()
1748    }
1749}
1750
1751impl<T> IntoPy<PyObject> for &Bound<'_, T> {
1752    /// Converts `&Bound` instance -> PyObject, increasing the reference count.
1753    #[inline]
1754    fn into_py(self, py: Python<'_>) -> PyObject {
1755        self.to_object(py)
1756    }
1757}
1758
1759unsafe impl<T> crate::AsPyPointer for Py<T> {
1760    /// Gets the underlying FFI pointer, returns a borrowed pointer.
1761    #[inline]
1762    fn as_ptr(&self) -> *mut ffi::PyObject {
1763        self.0.as_ptr()
1764    }
1765}
1766
1767#[cfg(feature = "gil-refs")]
1768impl<T> std::convert::From<&'_ T> for PyObject
1769where
1770    T: PyNativeType,
1771{
1772    #[inline]
1773    fn from(obj: &T) -> Self {
1774        obj.as_borrowed().to_owned().into_any().unbind()
1775    }
1776}
1777
1778impl<T> std::convert::From<Py<T>> for PyObject
1779where
1780    T: AsRef<PyAny>,
1781{
1782    #[inline]
1783    fn from(other: Py<T>) -> Self {
1784        other.into_any()
1785    }
1786}
1787
1788impl<T> std::convert::From<Bound<'_, T>> for PyObject
1789where
1790    T: AsRef<PyAny>,
1791{
1792    #[inline]
1793    fn from(other: Bound<'_, T>) -> Self {
1794        let py = other.py();
1795        other.into_py(py)
1796    }
1797}
1798
1799impl<T> std::convert::From<Bound<'_, T>> for Py<T> {
1800    #[inline]
1801    fn from(other: Bound<'_, T>) -> Self {
1802        other.unbind()
1803    }
1804}
1805
1806// `&PyCell<T>` can be converted to `Py<T>`
1807#[cfg(feature = "gil-refs")]
1808#[allow(deprecated)]
1809impl<T> std::convert::From<&crate::PyCell<T>> for Py<T>
1810where
1811    T: PyClass,
1812{
1813    fn from(cell: &crate::PyCell<T>) -> Self {
1814        cell.as_borrowed().to_owned().unbind()
1815    }
1816}
1817
1818impl<'a, T> std::convert::From<PyRef<'a, T>> for Py<T>
1819where
1820    T: PyClass,
1821{
1822    fn from(pyref: PyRef<'a, T>) -> Self {
1823        unsafe { Py::from_borrowed_ptr(pyref.py(), pyref.as_ptr()) }
1824    }
1825}
1826
1827impl<'a, T> std::convert::From<PyRefMut<'a, T>> for Py<T>
1828where
1829    T: PyClass<Frozen = False>,
1830{
1831    fn from(pyref: PyRefMut<'a, T>) -> Self {
1832        unsafe { Py::from_borrowed_ptr(pyref.py(), pyref.as_ptr()) }
1833    }
1834}
1835
1836/// If the GIL is held this increments `self`'s reference count.
1837/// Otherwise, it will panic.
1838///
1839/// Only available if the `py-clone` feature is enabled.
1840#[cfg(feature = "py-clone")]
1841impl<T> Clone for Py<T> {
1842    #[track_caller]
1843    fn clone(&self) -> Self {
1844        unsafe {
1845            gil::register_incref(self.0);
1846        }
1847        Self(self.0, PhantomData)
1848    }
1849}
1850
1851/// Dropping a `Py` instance decrements the reference count
1852/// on the object by one if the GIL is held.
1853///
1854/// Otherwise and by default, this registers the underlying pointer to have its reference count
1855/// decremented the next time PyO3 acquires the GIL.
1856///
1857/// However, if the `pyo3_disable_reference_pool` conditional compilation flag
1858/// is enabled, it will abort the process.
1859impl<T> Drop for Py<T> {
1860    #[track_caller]
1861    fn drop(&mut self) {
1862        unsafe {
1863            gil::register_decref(self.0);
1864        }
1865    }
1866}
1867
1868impl<T> FromPyObject<'_> for Py<T>
1869where
1870    T: PyTypeCheck,
1871{
1872    /// Extracts `Self` from the source `PyObject`.
1873    fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Self> {
1874        ob.extract::<Bound<'_, T>>().map(Bound::unbind)
1875    }
1876}
1877
1878impl<'py, T> FromPyObject<'py> for Bound<'py, T>
1879where
1880    T: PyTypeCheck,
1881{
1882    /// Extracts `Self` from the source `PyObject`.
1883    fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> {
1884        ob.downcast().cloned().map_err(Into::into)
1885    }
1886}
1887
1888/// `Py<T>` can be used as an error when T is an Error.
1889///
1890/// However for GIL lifetime reasons, cause() cannot be implemented for `Py<T>`.
1891/// Use .as_ref() to get the GIL-scoped error if you need to inspect the cause.
1892#[cfg(feature = "gil-refs")]
1893impl<T> std::error::Error for Py<T>
1894where
1895    T: std::error::Error + PyTypeInfo,
1896    T::AsRefTarget: std::fmt::Display,
1897{
1898}
1899
1900impl<T> std::fmt::Display for Py<T>
1901where
1902    T: PyTypeInfo,
1903{
1904    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1905        Python::with_gil(|py| std::fmt::Display::fmt(self.bind(py), f))
1906    }
1907}
1908
1909impl<T> std::fmt::Debug for Py<T> {
1910    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1911        f.debug_tuple("Py").field(&self.0.as_ptr()).finish()
1912    }
1913}
1914
1915/// A commonly-used alias for `Py<PyAny>`.
1916///
1917/// This is an owned reference a Python object without any type information. This value can also be
1918/// safely sent between threads.
1919///
1920/// See the documentation for [`Py`](struct.Py.html).
1921pub type PyObject = Py<PyAny>;
1922
1923impl PyObject {
1924    /// Deprecated form of [`PyObject::downcast_bound`]
1925    #[cfg(feature = "gil-refs")]
1926    #[deprecated(
1927        since = "0.21.0",
1928        note = "`PyObject::downcast` will be replaced by `PyObject::downcast_bound` in a future PyO3 version"
1929    )]
1930    #[inline]
1931    pub fn downcast<'py, T>(
1932        &'py self,
1933        py: Python<'py>,
1934    ) -> Result<&'py T, crate::err::PyDowncastError<'py>>
1935    where
1936        T: PyTypeCheck<AsRefTarget = T>,
1937    {
1938        self.downcast_bound::<T>(py)
1939            .map(Bound::as_gil_ref)
1940            .map_err(crate::err::PyDowncastError::from_downcast_err)
1941    }
1942    /// Downcast this `PyObject` to a concrete Python type or pyclass.
1943    ///
1944    /// Note that you can often avoid downcasting yourself by just specifying
1945    /// the desired type in function or method signatures.
1946    /// However, manual downcasting is sometimes necessary.
1947    ///
1948    /// For extracting a Rust-only type, see [`Py::extract`](struct.Py.html#method.extract).
1949    ///
1950    /// # Example: Downcasting to a specific Python object
1951    ///
1952    /// ```rust
1953    /// use pyo3::prelude::*;
1954    /// use pyo3::types::{PyDict, PyList};
1955    ///
1956    /// Python::with_gil(|py| {
1957    ///     let any: PyObject = PyDict::new_bound(py).into();
1958    ///
1959    ///     assert!(any.downcast_bound::<PyDict>(py).is_ok());
1960    ///     assert!(any.downcast_bound::<PyList>(py).is_err());
1961    /// });
1962    /// ```
1963    ///
1964    /// # Example: Getting a reference to a pyclass
1965    ///
1966    /// This is useful if you want to mutate a `PyObject` that
1967    /// might actually be a pyclass.
1968    ///
1969    /// ```rust
1970    /// # fn main() -> Result<(), pyo3::PyErr> {
1971    /// use pyo3::prelude::*;
1972    ///
1973    /// #[pyclass]
1974    /// struct Class {
1975    ///     i: i32,
1976    /// }
1977    ///
1978    /// Python::with_gil(|py| {
1979    ///     let class: PyObject = Py::new(py, Class { i: 0 }).unwrap().into_py(py);
1980    ///
1981    ///     let class_bound = class.downcast_bound::<Class>(py)?;
1982    ///
1983    ///     class_bound.borrow_mut().i += 1;
1984    ///
1985    ///     // Alternatively you can get a `PyRefMut` directly
1986    ///     let class_ref: PyRefMut<'_, Class> = class.extract(py)?;
1987    ///     assert_eq!(class_ref.i, 1);
1988    ///     Ok(())
1989    /// })
1990    /// # }
1991    /// ```
1992    #[inline]
1993    pub fn downcast_bound<'py, T>(
1994        &self,
1995        py: Python<'py>,
1996    ) -> Result<&Bound<'py, T>, DowncastError<'_, 'py>>
1997    where
1998        T: PyTypeCheck,
1999    {
2000        self.bind(py).downcast()
2001    }
2002
2003    /// Deprecated form of [`PyObject::downcast_bound_unchecked`]
2004    ///
2005    /// # Safety
2006    ///
2007    /// Callers must ensure that the type is valid or risk type confusion.
2008    #[cfg(feature = "gil-refs")]
2009    #[deprecated(
2010        since = "0.21.0",
2011        note = "`PyObject::downcast_unchecked` will be replaced by `PyObject::downcast_bound_unchecked` in a future PyO3 version"
2012    )]
2013    #[inline]
2014    pub unsafe fn downcast_unchecked<'py, T>(&'py self, py: Python<'py>) -> &T
2015    where
2016        T: HasPyGilRef<AsRefTarget = T>,
2017    {
2018        self.downcast_bound_unchecked::<T>(py).as_gil_ref()
2019    }
2020
2021    /// Casts the PyObject to a concrete Python object type without checking validity.
2022    ///
2023    /// # Safety
2024    ///
2025    /// Callers must ensure that the type is valid or risk type confusion.
2026    #[inline]
2027    pub unsafe fn downcast_bound_unchecked<'py, T>(&self, py: Python<'py>) -> &Bound<'py, T> {
2028        self.bind(py).downcast_unchecked()
2029    }
2030}
2031
2032#[cfg(test)]
2033mod tests {
2034    use super::{Bound, Py, PyObject};
2035    use crate::types::{dict::IntoPyDict, PyAnyMethods, PyCapsule, PyDict, PyString};
2036    use crate::{ffi, Borrowed, PyAny, PyResult, Python, ToPyObject};
2037
2038    #[test]
2039    fn test_call() {
2040        Python::with_gil(|py| {
2041            let obj = py.get_type_bound::<PyDict>().to_object(py);
2042
2043            let assert_repr = |obj: &Bound<'_, PyAny>, expected: &str| {
2044                assert_eq!(obj.repr().unwrap(), expected);
2045            };
2046
2047            assert_repr(obj.call0(py).unwrap().bind(py), "{}");
2048            assert_repr(obj.call1(py, ()).unwrap().bind(py), "{}");
2049            assert_repr(obj.call_bound(py, (), None).unwrap().bind(py), "{}");
2050
2051            assert_repr(obj.call1(py, ((('x', 1),),)).unwrap().bind(py), "{'x': 1}");
2052            assert_repr(
2053                obj.call_bound(py, (), Some(&[('x', 1)].into_py_dict_bound(py)))
2054                    .unwrap()
2055                    .bind(py),
2056                "{'x': 1}",
2057            );
2058        })
2059    }
2060
2061    #[test]
2062    fn test_call_for_non_existing_method() {
2063        Python::with_gil(|py| {
2064            let obj: PyObject = PyDict::new_bound(py).into();
2065            assert!(obj.call_method0(py, "asdf").is_err());
2066            assert!(obj
2067                .call_method_bound(py, "nonexistent_method", (1,), None)
2068                .is_err());
2069            assert!(obj.call_method0(py, "nonexistent_method").is_err());
2070            assert!(obj.call_method1(py, "nonexistent_method", (1,)).is_err());
2071        });
2072    }
2073
2074    #[test]
2075    fn py_from_dict() {
2076        let dict: Py<PyDict> = Python::with_gil(|py| {
2077            let native = PyDict::new_bound(py);
2078            Py::from(native)
2079        });
2080
2081        Python::with_gil(move |py| {
2082            assert_eq!(dict.get_refcnt(py), 1);
2083        });
2084    }
2085
2086    #[test]
2087    fn pyobject_from_py() {
2088        Python::with_gil(|py| {
2089            let dict: Py<PyDict> = PyDict::new_bound(py).unbind();
2090            let cnt = dict.get_refcnt(py);
2091            let p: PyObject = dict.into();
2092            assert_eq!(p.get_refcnt(py), cnt);
2093        });
2094    }
2095
2096    #[test]
2097    fn attr() -> PyResult<()> {
2098        use crate::types::PyModule;
2099
2100        Python::with_gil(|py| {
2101            const CODE: &str = r#"
2102class A:
2103    pass
2104a = A()
2105   "#;
2106            let module = PyModule::from_code_bound(py, CODE, "", "")?;
2107            let instance: Py<PyAny> = module.getattr("a")?.into();
2108
2109            instance.getattr(py, "foo").unwrap_err();
2110
2111            instance.setattr(py, "foo", "bar")?;
2112
2113            assert!(instance
2114                .getattr(py, "foo")?
2115                .bind(py)
2116                .eq(PyString::new_bound(py, "bar"))?);
2117
2118            instance.getattr(py, "foo")?;
2119            Ok(())
2120        })
2121    }
2122
2123    #[test]
2124    fn pystring_attr() -> PyResult<()> {
2125        use crate::types::PyModule;
2126
2127        Python::with_gil(|py| {
2128            const CODE: &str = r#"
2129class A:
2130    pass
2131a = A()
2132   "#;
2133            let module = PyModule::from_code_bound(py, CODE, "", "")?;
2134            let instance: Py<PyAny> = module.getattr("a")?.into();
2135
2136            let foo = crate::intern!(py, "foo");
2137            let bar = crate::intern!(py, "bar");
2138
2139            instance.getattr(py, foo).unwrap_err();
2140            instance.setattr(py, foo, bar)?;
2141            assert!(instance.getattr(py, foo)?.bind(py).eq(bar)?);
2142            Ok(())
2143        })
2144    }
2145
2146    #[test]
2147    fn invalid_attr() -> PyResult<()> {
2148        Python::with_gil(|py| {
2149            let instance: Py<PyAny> = py.eval_bound("object()", None, None)?.into();
2150
2151            instance.getattr(py, "foo").unwrap_err();
2152
2153            // Cannot assign arbitrary attributes to `object`
2154            instance.setattr(py, "foo", "bar").unwrap_err();
2155            Ok(())
2156        })
2157    }
2158
2159    #[test]
2160    fn test_py2_from_py_object() {
2161        Python::with_gil(|py| {
2162            let instance = py.eval_bound("object()", None, None).unwrap();
2163            let ptr = instance.as_ptr();
2164            let instance: Bound<'_, PyAny> = instance.extract().unwrap();
2165            assert_eq!(instance.as_ptr(), ptr);
2166        })
2167    }
2168
2169    #[test]
2170    fn test_py2_into_py_object() {
2171        Python::with_gil(|py| {
2172            let instance = py
2173                .eval_bound("object()", None, None)
2174                .unwrap()
2175                .as_borrowed()
2176                .to_owned();
2177            let ptr = instance.as_ptr();
2178            let instance: PyObject = instance.clone().unbind();
2179            assert_eq!(instance.as_ptr(), ptr);
2180        })
2181    }
2182
2183    #[test]
2184    #[allow(deprecated)]
2185    fn test_is_ellipsis() {
2186        Python::with_gil(|py| {
2187            let v = py
2188                .eval_bound("...", None, None)
2189                .map_err(|e| e.display(py))
2190                .unwrap()
2191                .to_object(py);
2192
2193            assert!(v.is_ellipsis());
2194
2195            let not_ellipsis = 5.to_object(py);
2196            assert!(!not_ellipsis.is_ellipsis());
2197        });
2198    }
2199
2200    #[test]
2201    fn test_debug_fmt() {
2202        Python::with_gil(|py| {
2203            let obj = "hello world".to_object(py).into_bound(py);
2204            assert_eq!(format!("{:?}", obj), "'hello world'");
2205        });
2206    }
2207
2208    #[test]
2209    fn test_display_fmt() {
2210        Python::with_gil(|py| {
2211            let obj = "hello world".to_object(py).into_bound(py);
2212            assert_eq!(format!("{}", obj), "hello world");
2213        });
2214    }
2215
2216    #[test]
2217    fn test_bound_as_any() {
2218        Python::with_gil(|py| {
2219            let obj = PyString::new_bound(py, "hello world");
2220            let any = obj.as_any();
2221            assert_eq!(any.as_ptr(), obj.as_ptr());
2222        });
2223    }
2224
2225    #[test]
2226    fn test_bound_into_any() {
2227        Python::with_gil(|py| {
2228            let obj = PyString::new_bound(py, "hello world");
2229            let any = obj.clone().into_any();
2230            assert_eq!(any.as_ptr(), obj.as_ptr());
2231        });
2232    }
2233
2234    #[test]
2235    fn test_bound_py_conversions() {
2236        Python::with_gil(|py| {
2237            let obj: Bound<'_, PyString> = PyString::new_bound(py, "hello world");
2238            let obj_unbound: &Py<PyString> = obj.as_unbound();
2239            let _: &Bound<'_, PyString> = obj_unbound.bind(py);
2240
2241            let obj_unbound: Py<PyString> = obj.unbind();
2242            let obj: Bound<'_, PyString> = obj_unbound.into_bound(py);
2243
2244            assert_eq!(obj, "hello world");
2245        });
2246    }
2247
2248    #[test]
2249    fn bound_from_borrowed_ptr_constructors() {
2250        // More detailed tests of the underlying semantics in pycell.rs
2251        Python::with_gil(|py| {
2252            fn check_drop<'py>(
2253                py: Python<'py>,
2254                method: impl FnOnce(*mut ffi::PyObject) -> Bound<'py, PyAny>,
2255            ) {
2256                let mut dropped = false;
2257                let capsule = PyCapsule::new_bound_with_destructor(
2258                    py,
2259                    (&mut dropped) as *mut _ as usize,
2260                    None,
2261                    |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) },
2262                )
2263                .unwrap();
2264
2265                let bound = method(capsule.as_ptr());
2266                assert!(!dropped);
2267
2268                // creating the bound should have increased the refcount
2269                drop(capsule);
2270                assert!(!dropped);
2271
2272                // dropping the bound should now also decrease the refcount and free the object
2273                drop(bound);
2274                assert!(dropped);
2275            }
2276
2277            check_drop(py, |ptr| unsafe { Bound::from_borrowed_ptr(py, ptr) });
2278            check_drop(py, |ptr| unsafe {
2279                Bound::from_borrowed_ptr_or_opt(py, ptr).unwrap()
2280            });
2281            check_drop(py, |ptr| unsafe {
2282                Bound::from_borrowed_ptr_or_err(py, ptr).unwrap()
2283            });
2284        })
2285    }
2286
2287    #[test]
2288    fn borrowed_ptr_constructors() {
2289        // More detailed tests of the underlying semantics in pycell.rs
2290        Python::with_gil(|py| {
2291            fn check_drop<'py>(
2292                py: Python<'py>,
2293                method: impl FnOnce(&*mut ffi::PyObject) -> Borrowed<'_, 'py, PyAny>,
2294            ) {
2295                let mut dropped = false;
2296                let capsule = PyCapsule::new_bound_with_destructor(
2297                    py,
2298                    (&mut dropped) as *mut _ as usize,
2299                    None,
2300                    |ptr, _| unsafe { std::ptr::write(ptr as *mut bool, true) },
2301                )
2302                .unwrap();
2303
2304                let ptr = &capsule.as_ptr();
2305                let _borrowed = method(ptr);
2306                assert!(!dropped);
2307
2308                // creating the borrow should not have increased the refcount
2309                drop(capsule);
2310                assert!(dropped);
2311            }
2312
2313            check_drop(py, |&ptr| unsafe { Borrowed::from_ptr(py, ptr) });
2314            check_drop(py, |&ptr| unsafe {
2315                Borrowed::from_ptr_or_opt(py, ptr).unwrap()
2316            });
2317            check_drop(py, |&ptr| unsafe {
2318                Borrowed::from_ptr_or_err(py, ptr).unwrap()
2319            });
2320        })
2321    }
2322
2323    #[test]
2324    fn explicit_drop_ref() {
2325        Python::with_gil(|py| {
2326            let object: Py<PyDict> = PyDict::new_bound(py).unbind();
2327            let object2 = object.clone_ref(py);
2328
2329            assert_eq!(object.as_ptr(), object2.as_ptr());
2330            assert_eq!(object.get_refcnt(py), 2);
2331
2332            object.drop_ref(py);
2333
2334            assert_eq!(object2.get_refcnt(py), 1);
2335
2336            object2.drop_ref(py);
2337        });
2338    }
2339
2340    #[cfg(feature = "macros")]
2341    mod using_macros {
2342        use super::*;
2343
2344        #[crate::pyclass(crate = "crate")]
2345        struct SomeClass(i32);
2346
2347        #[test]
2348        fn py_borrow_methods() {
2349            // More detailed tests of the underlying semantics in pycell.rs
2350            Python::with_gil(|py| {
2351                let instance = Py::new(py, SomeClass(0)).unwrap();
2352                assert_eq!(instance.borrow(py).0, 0);
2353                assert_eq!(instance.try_borrow(py).unwrap().0, 0);
2354                assert_eq!(instance.borrow_mut(py).0, 0);
2355                assert_eq!(instance.try_borrow_mut(py).unwrap().0, 0);
2356
2357                instance.borrow_mut(py).0 = 123;
2358
2359                assert_eq!(instance.borrow(py).0, 123);
2360                assert_eq!(instance.try_borrow(py).unwrap().0, 123);
2361                assert_eq!(instance.borrow_mut(py).0, 123);
2362                assert_eq!(instance.try_borrow_mut(py).unwrap().0, 123);
2363            })
2364        }
2365
2366        #[test]
2367        fn bound_borrow_methods() {
2368            // More detailed tests of the underlying semantics in pycell.rs
2369            Python::with_gil(|py| {
2370                let instance = Bound::new(py, SomeClass(0)).unwrap();
2371                assert_eq!(instance.borrow().0, 0);
2372                assert_eq!(instance.try_borrow().unwrap().0, 0);
2373                assert_eq!(instance.borrow_mut().0, 0);
2374                assert_eq!(instance.try_borrow_mut().unwrap().0, 0);
2375
2376                instance.borrow_mut().0 = 123;
2377
2378                assert_eq!(instance.borrow().0, 123);
2379                assert_eq!(instance.try_borrow().unwrap().0, 123);
2380                assert_eq!(instance.borrow_mut().0, 123);
2381                assert_eq!(instance.try_borrow_mut().unwrap().0, 123);
2382            })
2383        }
2384
2385        #[crate::pyclass(frozen, crate = "crate")]
2386        struct FrozenClass(i32);
2387
2388        #[test]
2389        fn test_frozen_get() {
2390            Python::with_gil(|py| {
2391                for i in 0..10 {
2392                    let instance = Py::new(py, FrozenClass(i)).unwrap();
2393                    assert_eq!(instance.get().0, i);
2394
2395                    assert_eq!(instance.bind(py).get().0, i);
2396                }
2397            })
2398        }
2399
2400        #[test]
2401        #[cfg(feature = "gil-refs")]
2402        #[allow(deprecated)]
2403        fn cell_tryfrom() {
2404            use crate::{PyCell, PyTryInto};
2405            // More detailed tests of the underlying semantics in pycell.rs
2406            Python::with_gil(|py| {
2407                let instance: &PyAny = Py::new(py, SomeClass(0)).unwrap().into_ref(py);
2408                let _: &PyCell<SomeClass> = PyTryInto::try_into(instance).unwrap();
2409                let _: &PyCell<SomeClass> = PyTryInto::try_into_exact(instance).unwrap();
2410            })
2411        }
2412    }
2413}