macro_rules! intern { ($py: expr, $text: expr) => { ... }; }
Expand description
Interns text
as a Python string and stores a reference to it in static storage.
A reference to the same Python string is returned on each invocation.
ยงExample: Using intern!
to avoid needlessly recreating the same Python string
use pyo3::intern;
#[pyfunction]
fn create_dict(py: Python<'_>) -> PyResult<Bound<'_, PyDict>> {
let dict = PyDict::new_bound(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<Bound<'_, PyDict>> {
let dict = PyDict::new_bound(py);
// ๐ A `PyString` is created once and reused
// for the lifetime of the program.
dict.set_item(intern!(py, "foo"), 42)?;
Ok(dict)
}