Skip to content

pytypes: Add iterable_t<T> #2950

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,10 @@ template <>
struct handle_type_name<iterable> {
static constexpr auto name = const_name("Iterable");
};
template <typename T>
struct handle_type_name<iterable_t<T>> {
static constexpr auto name = const_name("Iterable[") + type_caster<T>::name + const_name("]");
};
template <>
struct handle_type_name<iterator> {
static constexpr auto name = const_name("Iterator");
Expand Down
46 changes: 46 additions & 0 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -966,6 +966,10 @@ inline bool PyIterable_Check(PyObject *obj) {
return false;
}

// Defer definition until we have object_api<> available.
template <typename T>
bool PyIterableT_Check(PyObject *obj);

inline bool PyNone_Check(PyObject *o) { return o == Py_None; }
inline bool PyEllipsis_Check(PyObject *o) { return o == Py_Ellipsis; }

Expand Down Expand Up @@ -1177,6 +1181,20 @@ class iterable : public object {
PYBIND11_OBJECT_DEFAULT(iterable, object, detail::PyIterable_Check)
};

/// Provides similar interface to `iterable`, but constraining the intended
/// type.
/// @warning Due to technical reasons, this is constrained in two ways:
/// - Due to how `isinstance<T>()` works, this does *not* work for iterables of
/// type-converted values (e.g. `int`).
/// - Because we must check the contained types within the iterable (for
/// overloads), we must iterate through the iterable. For this reason, the
/// iterable should *not* be exhaustible (e.g., iterator, generator).
template <typename T>
class iterable_t : public iterable {
public:
PYBIND11_OBJECT_DEFAULT(iterable_t, iterable, detail::PyIterableT_Check<T>)
};

class bytes;

class str : public object {
Expand Down Expand Up @@ -2109,5 +2127,33 @@ PYBIND11_MATH_OPERATOR_BINARY(operator>>=, PyNumber_InPlaceRshift)
#undef PYBIND11_MATH_OPERATOR_UNARY
#undef PYBIND11_MATH_OPERATOR_BINARY

template <typename T>
bool PyIterableT_Check(PyObject *obj) {
PyObject *iter = PyObject_GetIter(obj);
bool good = false;
if (iter) {
if (iter == obj) {
// If they are the same, then that's bad! For now, just throw a
// cast error.
Py_DECREF(iter);
throw cast_error("iterable_t<T> cannot be used with exhaustible iterables "
"(e.g., iterators, generators).");
}
good = true;
// Now that we know that the iterable `obj` will not be exhausted,
// let's check the contained types.
for (handle h : handle(iter)) {
if (!isinstance<T>(h)) {
good = false;
break;
}
}
Py_DECREF(iter);
} else {
PyErr_Clear();
}
return good;
}

PYBIND11_NAMESPACE_END(detail)
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
5 changes: 5 additions & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ TEST_SUBMODULE(pytypes, m) {
m.def("get_iterator", [] { return py::iterator(); });
// test_iterable
m.def("get_iterable", [] { return py::iterable(); });
// test_iterable_t
m.def("get_iterable_t", [] { return py::iterable_t<py::str>(); });
// test_iterable_t_overloads
m.def("accept_iterable_t", [](const py::iterable_t<py::str> &) { return "str"; });
m.def("accept_iterable_t", [](const py::iterable_t<py::bytes> &) { return "bytes"; });
// test_float
m.def("get_float", [] { return py::float_(0.0f); });
// test_list
Expand Down
39 changes: 39 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,45 @@ def test_iterable(doc):
assert doc(m.get_iterable) == "get_iterable() -> Iterable"


def test_iterable_t(doc):
assert doc(m.get_iterable_t) == "get_iterable_t() -> Iterable[str]"


def test_iterable_t_overloads():
# Empty: First one wins.
list_empty = []
set_empty = set()
assert m.accept_iterable_t(list_empty) == "str"
assert m.accept_iterable_t(set_empty) == "str"
# Negative: Exhaustible iterables (e.g. iterators, generators).
gen_empty = (x for x in set_empty)
with pytest.raises(RuntimeError):
m.accept_iterable_t(gen_empty)
iter_empty = iter(list_empty)
with pytest.raises(RuntimeError):
m.accept_iterable_t(iter_empty)

# Str.
list_of_str = ["hey", "you"]
set_of_str = {"hey", "you"}
assert m.accept_iterable_t(list_of_str) == "str"
assert m.accept_iterable_t(set_of_str) == "str"
# - Negative: Not fully `str`.
list_of_str_and_then_some = ["hey", 0]
with pytest.raises(TypeError):
m.accept_iterable_t(list_of_str_and_then_some)

# Bytes.
list_of_bytes = [b"hey", b"you"]
set_of_bytes = {b"hey", b"you"}
assert m.accept_iterable_t(list_of_bytes) == "bytes"
assert m.accept_iterable_t(set_of_bytes) == "bytes"
# - Negative: Not fully `bytes`.
list_of_bytes_and_then_some = [b"hey", 0]
with pytest.raises(TypeError):
m.accept_iterable_t(list_of_bytes_and_then_some)


def test_float(doc):
assert doc(m.get_float) == "get_float() -> float"

Expand Down