iter() and iterators
-
User
__iter__and__next__methods cannot suspend when driven byfor, comprehensions, collection constructors, or native iterator adaptors. An external or OS call raisesNotImplementedErrorinside the method, where it can be caught. Directiter(),next()(including its default form), andfunctools.reduce()can suspend in these methods. -
iter(callable, sentinel)runscallablesynchronously, so one that calls an external/OS function cannot suspend and raisesNotImplementedError. Same limitation asmap/filter/sorted(key=...). -
iter(callable, sentinel)comparesresult == sentinel, where CPython comparessentinel == result; only observable if the two sides have asymmetric__eq__. -
A
StopIterationraised bycallablepropagates; CPython treats it as clean exhaustion and stops iterating. -
The vendored type stub is upstream typeshed’s verbatim, so
-tacceptsiter(obj)for an object with only__getitem__; Monty has no__getitem__iteration fallback and raisesTypeErrorat runtime. -
-tacceptsfor x in obj(though nota, b = obj) for a class that opts out of iteration with__iter__ = None, which raisesTypeErrorat runtime as it does in CPython. -
Built-in iterators do not expose their dunders as attributes:
hasattr(iter([1]), '__iter__')isFalse, where CPython reportsTrue. Iteration itself works; only attribute lookup of the dunder differs. This covers every built-in iterator, including theitertoolsadaptors. -
Iterator-specific attributes such as
__length_hint__are not exposed.