[Python-ideas] Make len() usable on a generator

Andrew Barnert abarnert at yahoo.com
Sat Oct 11 01:34:37 CEST 2014


On Oct 10, 2014, at 11:06, random832 at fastmail.us wrote:

> On Fri, Oct 10, 2014, at 11:09, Adam Jorgensen wrote:
>> I don't think it makes much sense for len() to work on generators and the
>> fact that sum() works isn't a good argument.
>> 
>> Summing the contents of a generator can make sense whereas attempting to
>> obtain the length of something which specifically does not define a
>> length
>> seems a little nonsensical to me...
> 
> Why doesn't it define a length? No, hear me out. Is there any reason
> that, for example, generator expressions on lists or ranges shouldn't be
> read-only views instead of generators?

When I first started playing with Swift, I was impressed by the fact that they tried to make as many things as possible into views instead of iterators. (I'm going to use Python terminology here, because for some reason they came up with new terms for everything, making sure that every word was a false cognate with something in either Python, C++, or Haskell...) 

Map returns a view which can be indexed and in general acts like a sequence. Filter returns a view that can be indexed by non-random-accessible indices (you can start with begin or end and ++ or -- from there). And so on.

But when you start trying to build your own views, iterators, and sequences, or just trying to chain together the existing ones, everything gets a lot harder. It's nowhere near as nice as Python, C++, or Haskell in practice, even though it combines the best of all three in toy examples.

That's not to say that a good design for this stuff isn't possible, just that it's obviously not trivial.

The if example is a good illustration of this. If a genexpr is a sequence iff it has exactly 1 for clause and 0 if clauses, becoming a non-random-accessible view if it has a second for or any if, that makes it a lot harder to read, document, or teach code that uses genexprs (unless that code just ignores all view functionality and treats everything as a generic iterable).


More information about the Python-ideas mailing list