[go: up one dir, main page]

pyo3/
instance.rs

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