pub trait PyIterProtocol<'p>: PyClass {
    fn __iter__(slf: Self::Receiver) -> Self::Result
    where
        Self: PyIterIterProtocol<'p>
, { ... } fn __next__(slf: Self::Receiver) -> Self::Result
    where
        Self: PyIterNextProtocol<'p>
, { ... } }
👎 Deprecated since 0.16.0:

prefer #[pymethods] to #[pyproto]

Available on crate feature pyproto only.
Expand description

Python Iterator Interface.

Check CPython doc for more.

Examples

The following example shows how to implement a simple Python iterator in Rust which yields the integers 1 to 5, before raising StopIteration("Ended").

use pyo3::class::iter::IterNextOutput;
use pyo3::prelude::*;
use pyo3::PyIterProtocol;

#[pyclass]
struct Iter {
    count: usize,
}

#[pyproto]
impl PyIterProtocol for Iter {
    fn __next__(mut slf: PyRefMut<Self>) -> IterNextOutput<usize, &'static str> {
        if slf.count < 5 {
            slf.count += 1;
            IterNextOutput::Yield(slf.count)
        } else {
            IterNextOutput::Return("Ended")
        }
    }
}

Provided Methods

👎 Deprecated since 0.16.0:

prefer #[pymethods] to #[pyproto]

👎 Deprecated since 0.16.0:

prefer #[pymethods] to #[pyproto]

Implementors