Skip to content

Replace the return type of make_iterator from "iterator" to "typing.Iterator" #2270

Closed
@AWhetter

Description

@AWhetter

Issue description

Currently when declaring a method that returns the result of py::make_iterator(), the type signature in the docstring uses the return type iterator, which is not a valid Python type. In the example below we see the docstring:

__iter__(self: numbers.Numbers) -> iterator\n

I was hoping that the type could instead be switched to either typing.Iterator or Iterator.

__iter__(self: numbers.Numbers) -> typing.Iterator\n

The use case where this is coming up:
I'm generating type stubs of a pybind module using stubgen. When running mypy with the generated stubs I see the following error:

error: name 'iterator' is not defined

Reproducible example code

#include <pybind11/pybind11.h>

namespace py = pybind11;

static const std::vector<string> numbers = {"1", "2", "3"};

class Numbers {
    std::vector<int>::iterator begin() { return numbers.begin(); }
    std::vector<int>::iterator end() { return numbers.end(); }
}

PYBIND11_MODULE(numbers, m) {
    py::class<Numbers>(m, "Numbers")
        .def("__iter__",
            [](const Numbers& self) {
                return py::make_iterator(self.begin(), self.end());
            },
            py::keep_alive<0, 1>()
        )
    ;
}
>>> import numbers
>>> numbers.Numbers.__iter__.__doc__
'__iter__(self: numbers.Numbers) -> iterator\n'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions