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