
On 11/20/2014 04:01 AM, Nick Coghlan wrote:
This idea occurred to me in context of PEP 479 and the "or stop()" hack for generator expressions. I'm not a big enough fan of the idea to pursue it myself, but if anyone is bothered by the prospect of PEP 479 taking the "or stop()" technique away, this may be worth pursuing further.
As a reminder of how the hack works, the following generator:
def takewhile(iterable, pred): ... for x in iter(iterable): ... if not pred(x): ... return ... yield x ... list(takewhile(range(10), (lambda x: x < 5))) [0, 1, 2, 3, 4]
Just a note: If this generator was used on an iterator more than once it would drop items between groups. Takewhile fits the peek-ahead pattern I mentioned in an earlier thread that groupby matches. I think groupby manages to hide the looked ahead value in the yield path, but it still does look ahead, just not in an obvious way. It's my understanding looking ahead is problomatic for genrators because they may have side effects when next() is called on them. Like reading input or writing output, or accessing some other object outside the generator. It seams to me that most (if not all) partial iterations will either want to yield the "last" value tested, or stop "before" the last value tested. The generator expression version of the above has issues with both of those. Cheers, Ron