Why don't generators execute until first yield?
Martin Sand Christensen
msc at es.aau.dk
Wed May 7 06:48:44 EDT 2008
>>>>> "Ian" == Ian Kelly <ian.g.kelly at gmail.com> writes:
Ian> Isn't lazy evaluation sort of the whole point of replacing a list
Ian> with an iterator? Besides which, running up to the first yield when
Ian> instantiated would make the generator's first iteration
Ian> inconsistent with the remaining iterations.
That wasn't my idea, although that may not have come across quite
clearly enough. I wanted the generator to immediately run until right
before the first yield so that the first call to next() would start with
the first yield.
My objection is that generators _by default_ have different semantics
than the rest of the language. Lazy evaluation as a concept is great for
all the benefits it can provide, but, as I've illustrated, strictly lazy
evaluation semantics can be somewhat surprising at times and lead to
problems that are hard to debug if you don't constantly bear the
difference in mind. In this respect, it seems to me that my suggestion
would be an improvement. I'm not any kind of expert on languages,
though, and I may very well be missing a part of the bigger picture that
makes it obvous why things should be as they are.
As for code to slightly change the semantics of generators, that doesn't
really address the issue as I see it: if you're going to apply such code
to your generators, you're probably doing it exactly because you're
aware of the difference in semantics, and you're not going to be
surprised by it. You may still want to change the semantics, but for
reasons that are irrelevant to my point.
Martin
More information about the Python-list
mailing list