Trait pyo3::class::iter::PyIterProtocol[][src]

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>
, { ... } }
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::prelude::*;
use pyo3::PyIterProtocol;
use pyo3::class::iter::IterNextOutput;

#[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

Implementors