pyo3::types

Module iter

Source
Expand description

Iteration over Python collections.

When working with a Python collection, one approach is to convert it to a Rust collection such as Vec or HashMap. However this is a relatively expensive operation. If you just want to visit all their items, consider iterating over the collections directly:

§Examples

use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3::ffi::c_str;

Python::with_gil(|py| {
    let dict = py.eval(c_str!("{'a':'b', 'c':'d'}"), None, None)?.downcast_into::<PyDict>()?;

    for (key, value) in &dict {
        println!("key: {}, value: {}", key, value);
    }

    Ok(())
})

If PyO3 detects that the collection is mutated during iteration, it will panic.

These iterators use Python’s C-API directly. However in certain cases, like when compiling for the Limited API and PyPy, the underlying structures are opaque and that may not be possible. In these cases the iterators are implemented by forwarding to PyIterator.

Structs§