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;
Python::with_gil(|py| {
let dict = py.eval_bound("{'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§
- Used by
PyTuple::iter_borrowed()
. - PyO3 implementation of an iterator for a Python
dict
object. - PyO3 implementation of an iterator for a Python
frozenset
object. - Used by
PyList::iter()
. - PyO3 implementation of an iterator for a Python
set
object. - Used by
PyTuple::into_iter()
.