Some time ago, I questioned the wisdom of adding the new iterator protocol to Python. Now I'm wiser, and I understand :)
Roundup 0.8 includes per-item access controls - for example, you can specify that users may only view / edit certain issues, or perhaps certain messages attached to issues. The HTML templating system now automatically filters out inaccessible items from listings. In one situation, it does so using an iterator:
class MultilinkIterator:
def __init__(self, classname, client, values):
self.classname = classname
self.client = client
self.values = values
self.id = -1
def next(self):
'''Return the next item, but skip inaccessible items.'''
check = self.client.db.security.hasPermission
userid = self.client.userid
while 1:
self.id += 1
if self.id >= len(self.values):
raise StopIteration
value = self.values[self.id]
if check('View', userid, self.classname, itemid=value):
return HTMLItem(self.client, self.classname, value)
def __iter__(self):
return self
Doing this using an old-style __getitem__ "iterator" would be much more difficult and messy.
Update: inspired by Bob's comment, I re-wrote it as a generator (my second ever ;)
def multilinkGenerator(classname, client, values):
id = -1
check = client.db.security.hasPermission
userid = client.userid
while 1:
id += 1
if id >= len(values):
raise StopIteration
value = values[id]
if check('View', userid, classname, itemid=value):
yield HTMLItem(client, classname, value)
I'm going to have so much fun playing with Python 2.3+ stuff* :)
*: Roundup's been holding me back ... until today's 0.8 release the minimum requirement was Python 2.1.