|
|
Monday, May 6, 2002 |
|
Fun With Generators "The great thing about this arrangement is that I can substitute a different block generating function with zero effort, as sizeAndDigest doesn't need to know how its data is being generated. I could have done that with saved state and a callback to get the next chunk of data, but generators are a lot simpler." [Deadly Bloody Serious] 1:50:55 PM blips[] |
|
Python Generators 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
8:51:39 AM blips[] |
|
Boolean type for Python 2.3 I should pay attention to the comp.lang.python mailing list more often, but Usenet newsgroups seem to be a much bigger pain in the ass in these days of Broadband - it's hard to know whether your provider, or your providers provider, will really offer any usenet service. Anyways, PEP 285 brings about True and False to the Python language as natural members for the first time. One of the areas this will help in is the reduction of code like this: return not not foo #the twin 'not not' keywords cast foo into a boolean statement and replace it with: return bool(foo) Which, while brief, avoids the headslam that boolean logic games like 'not not' can be. One place this will be especially beneficial is with XML-RPC and SOAP, and other means of communicating with languages that have (and expect!) booleans. It's been sufficient so far in Python to use any true value or any false value for boolean use, and 1 and 0 for basic usage, but that's hard to communicate over the wire. A Python function may return '1' as an integer value. But it can also be returning '1' to indicate truth (as in predicates like 'isinstance()').
So... Interesting. Never even knew it was up for debate, let alone accepted.
|