Macro pyo3::intern

source ·
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<&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)
}