There's a post on
Lambda the Ultimate today about
Generators and Abstraction, with reference to "Python".
Ruby has the concept of generators built in from the ground up. Last summer, I came across Ruby and started playing around with it, and annoyed everyone around me (I was working for
Zope Corporation who own PythonLabs) by going on and on about Ruby's object model and generators.
While I'm sure my little rants had little or nothing to do with the course of Python 2.2, it is nice to see Python picking up on simple generators, iterators, and the whole
new classes thing. It has me excited about Python again.
An interesting show of the power of generators and iterators comes from
PEP 279,
The enumerate() built-in function. It's a new built in function that gives to all collections (anything iterable) functionality similar to dict.items() (more specifically,
dict.iteritems()) which loops over the keys (index) and values (item) of a dictionary. This example, from the PEP itself, shows a good use of generators and iterators in action, keeping evaluation of a loop lazy while being able to index it:
def enumerate(collection):
'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...'
i = 0
it = iter(collection)
while 1:
yield (i, it.next())
i += 1