@@ -763,6 +763,39 @@ inline bool PyIterable_Check(PyObject *obj) {
763
763
}
764
764
}
765
765
766
+ template <typename T>
767
+ bool PyIterableT_Check (PyObject *obj) {
768
+ static_assert (
769
+ is_generic_type<T>::value || is_pyobject<T>::value,
770
+ " iterable_t can only be used with pyobjects and generic types "
771
+ " (py::class_<T>" );
772
+ PyObject *iter = PyObject_GetIter (obj);
773
+ if (iter) {
774
+ if (iter == obj) {
775
+ // If they are the same, then that's bad! For now, just throw a
776
+ // cast error.
777
+ Py_DECREF (iter);
778
+ throw cast_error (
779
+ " iterable_t<T> cannot be used with exhausitble iterables "
780
+ " (e.g., iterators, generators)." );
781
+ }
782
+ bool good = true ;
783
+ // Now that we know that the iterable `obj` will not be exhausted,
784
+ // let's check the contained types.
785
+ for (handle h : handle (iter)) {
786
+ if (!isinstance<T>(h)) {
787
+ good = false ;
788
+ break ;
789
+ }
790
+ }
791
+ Py_DECREF (iter);
792
+ return good;
793
+ } else {
794
+ PyErr_Clear ();
795
+ return false ;
796
+ }
797
+ }
798
+
766
799
inline bool PyNone_Check (PyObject *o) { return o == Py_None; }
767
800
inline bool PyEllipsis_Check (PyObject *o) { return o == Py_Ellipsis; }
768
801
@@ -953,17 +986,16 @@ class iterable : public object {
953
986
954
987
// / Provides similar interface to `iterable`, but constraining the intended
955
988
// / type.
956
- // / @warning Due to usage of `isinstance<T>()` in the related type-caster, this
957
- // / does *not* work for iterables of type-converted values (e.g. `int`).
989
+ // / @warning Due to technical reasons, this is constrained in two ways:
990
+ // / - Due to how `isinstance<T>()` works, this does *not* work for iterables of
991
+ // / type-converted values (e.g. `int`).
992
+ // / - Because we must check the contained types within the iterable (for
993
+ // / overloads), we must iterate through the iterable. For this reason, the
994
+ // / iterable should *not* be exhaustible (e.g., iterator, generator).
958
995
template <typename T>
959
- class iterable_t : public py :: iterable {
996
+ class iterable_t : public iterable {
960
997
public:
961
- // See type_caster specialization.
962
- static_assert (
963
- is_generic_type<T>::value || is_pyobject<T>::value,
964
- " iterable_t can only be used with pyobjects and generic types "
965
- " (py::class_<T>" );
966
- using py::iterable::iterable;
998
+ PYBIND11_OBJECT_DEFAULT (iterable_t , iterable, detail::PyIterableT_Check<T>)
967
999
};
968
1000
969
1001
class bytes ;
0 commit comments