Skip to content

Commit

Permalink
Add intern! macro which can be used to amortize the cost of creating …
Browse files Browse the repository at this point in the history
…Python objects by storing them inside a GILOnceCell.
  • Loading branch information
adamreichold committed Apr 3, 2022
1 parent 040ce86 commit a4629d7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Allow dependent crates to access config values from `pyo3-build-config` via cargo link dep env vars. [#2092](https://github.com/PyO3/pyo3/pull/2092)
- Added methods on `InterpreterConfig` to run Python scripts using the configured executable. [#2092](https://github.com/PyO3/pyo3/pull/2092)
- Added FFI definitions for `PyType_FromModuleAndSpec`, `PyType_GetModule`, `PyType_GetModuleState` and `PyModule_AddType`. [#2250](https://github.com/PyO3/pyo3/pull/2250)
- Add `intern!` macro which can be used to amortize the cost of creating Python objects by storing them inside a `GILOnceCell`. [#2269](https://github.com/PyO3/pyo3/pull/2269)

### Changed

Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Expand Up @@ -375,6 +375,7 @@ pub mod impl_;
mod instance;
pub mod marker;
pub mod marshal;
#[macro_use]
pub mod once_cell;
pub mod panic;
pub mod prelude;
Expand Down
43 changes: 43 additions & 0 deletions src/once_cell.rs
Expand Up @@ -101,3 +101,46 @@ impl<T> GILOnceCell<T> {
Ok(())
}
}

/// Converts `value` into a Python object and stores it in static storage. The same Python object
/// is returned on each invocation.
///
/// Because it is stored in a static, this object's destructor will not run.
///
/// # Example: Using `intern!` to avoid needlessly recreating the same object
///
/// ```
/// use pyo3::intern;
/// # use pyo3::{pyfunction, types::PyDict, PyResult, Python};
///
/// #[pyfunction]
/// fn create_dict(py: Python<'_>) -> PyResult<&PyDict> {
/// let dict = PyDict::new(py);
/// // 👇 A new `PyString` is created
/// // for every call of this function
/// dict.set_item("foo", 42)?;
/// Ok(dict)
/// }
///
/// #[pyfunction]
/// fn create_dict_faster(py: Python<'_>) -> PyResult<&PyDict> {
/// let dict = PyDict::new(py);
/// // 👇 A `PyString` is created once and reused
/// // for the lifetime of the program.
/// dict.set_item(intern!(py, "foo"), 42)?;
/// Ok(dict)
/// }
/// ```
#[macro_export]
macro_rules! intern {
($py: expr, $value: expr) => {{
static INTERNED: $crate::once_cell::GILOnceCell<$crate::PyObject> =
$crate::once_cell::GILOnceCell::new();

INTERNED
.get_or_init($py, || {
$crate::conversion::ToPyObject::to_object($value, $py)
})
.as_ref($py)
}};
}

0 comments on commit a4629d7

Please sign in to comment.