Skip to content

How to implement __iter__ when yielding a #[pyclass] type? #5168

Answered by Icxolu
aeshirey asked this question in Questions
Discussion options

You must be logged in to vote

I think you are looking for Py::borrow to get access to your container from within the iterator. Something like the following:

#[pymethods]
impl Container {
    ...

    fn __iter__(slf: Py<Self>) -> ContainerIterator {
        ContainerIterator {
            index: 0,
            container: slf,
        }
    }
}

#[pyclass]
struct ContainerIterator {
    index: usize,
    container: Py<Container>,
}

#[pymethods]
impl ContainerIterator {
    fn __iter__(slf: Py<Self>) -> Py<Self> {
        slf
    }

    fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<Item>> {
        let container = self.container.borrow(py); // borrow to get access to the container
        if self.index < co…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@aeshirey
Comment options

Answer selected by aeshirey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants