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