[Python-ideas] Generator syntax hooks?

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Tue Aug 8 14:45:31 EDT 2017

>>>>> Soni L. writes:
 > Steven d'Aprano writes:

 > > range(1000, 1000000)
 > > (x for x in range(1000, 1000000))  # waste of time and effort

 > Actually, those have different semantics!

That's not real important.  As Stefan Behnel points out, it's simple
(and efficient) to get iterator semantics by using iter().

The big issue here is that Python is not the kind of declarative
language where (x for x in int if 1_000 ≤ x ≤ 1_000_000)[1] is
natural to write, let alone easy to implement efficiently.  Aside from
the problem of (x for x in float if 1_000 ≤ x ≤ 1_000_000) (where
the answer is "just don't do that"), I can't think of any unbounded
collections in Python that aren't iterables, except some types.

That makes Steven's criticism pretty compelling.  If you need to
design a collection's __iter__ specially to allow it to decide whether
the subset that satisfies some condition is exhausted, why not just
subclass some appropriate existing collection with a more appropriate

[1]  See what I did there? ;-)

More information about the Python-ideas mailing list