pyo3_pytests/
dict_iter.rs1use pyo3::exceptions::PyRuntimeError;
2use pyo3::prelude::*;
3use pyo3::types::PyDict;
4
5#[pymodule]
6pub fn dict_iter(m: &Bound<'_, PyModule>) -> PyResult<()> {
7 m.add_class::<DictSize>()?;
8 Ok(())
9}
10
11#[pyclass]
12pub struct DictSize {
13 expected: u32,
14}
15
16#[pymethods]
17impl DictSize {
18 #[new]
19 fn new(expected: u32) -> Self {
20 DictSize { expected }
21 }
22
23 fn iter_dict(&mut self, _py: Python<'_>, dict: &Bound<'_, PyDict>) -> PyResult<u32> {
24 let mut seen = 0u32;
25 for (sym, values) in dict {
26 seen += 1;
27 println!(
28 "{:4}/{:4} iterations:{}=>{}",
29 seen, self.expected, sym, values
30 );
31 }
32
33 if seen == self.expected {
34 Ok(seen)
35 } else {
36 Err(PyErr::new::<PyRuntimeError, _>(format!(
37 "Expected {} iterations - performed {}",
38 self.expected, seen
39 )))
40 }
41 }
42}