pyo3/
instance.rs

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