From 769846e6b7eb49fd2618ac5944500b5dc6d23963 Mon Sep 17 00:00:00 2001 From: David Hewitt Date: Mon, 19 Feb 2024 22:53:24 +0000 Subject: [PATCH] docs: update example for storing Py in structs --- src/instance.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/instance.rs b/src/instance.rs index b83b69a20d3..188d05edd58 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -656,9 +656,14 @@ impl IntoPy for Borrowed<'_, '_, T> { /// These require passing in the [`Python<'py>`](crate::Python) token but are otherwise similar to the corresponding /// methods on [`PyAny`]. /// -/// # Example: Storing Python objects in structs +/// # Example: Storing Python objects in `#[pyclass]` structs +/// +/// Usually `Bound<'py, T>` is recommended for interacting with Python objects as its lifetime `'py` +/// is an association to the GIL and that enables many operations to be done as efficiently as possible. +/// +/// However, `#[pyclass]` structs cannot carry a lifetime, so `Py` is the only way to store +/// a Python object in a `#[pyclass]` struct. /// -/// As all the native Python objects only appear as references, storing them in structs doesn't work well. /// For example, this won't compile: /// /// ```compile_fail @@ -667,7 +672,7 @@ impl IntoPy for Borrowed<'_, '_, T> { /// # /// #[pyclass] /// struct Foo<'py> { -/// inner: &'py PyDict, +/// inner: Bound<'py, PyDict>, /// } /// /// impl Foo { @@ -675,9 +680,9 @@ impl IntoPy for Borrowed<'_, '_, T> { /// let foo = Python::with_gil(|py| { /// // `py` will only last for this scope. /// -/// // `&PyDict` derives its lifetime from `py` and +/// // `Bound<'py, PyDict>` inherits the GIL lifetime from `py` and /// // so won't be able to outlive this closure. -/// let dict: &PyDict = PyDict::new(py); +/// let dict: Bound<'_, PyDict> = PyDict::new_bound(py); /// /// // because `Foo` contains `dict` its lifetime /// // is now also tied to `py`.