Suggesting a new feature - "Inverse Generators"
Andrew Koenig
ark at acm.org
Fri Mar 25 11:18:47 EST 2005
"Jordan Rastrick" <jrastrick at student.usyd.edu.au> wrote in message
news:1111766687.125697.311420 at f14g2000cwb.googlegroups.com...
> def combineIntoRecord(): # This is an acceptor function
> optionalline = None # We may not get given a value for this line
> accept firstline
> accept secondline
> if condition(secondline):
> accept optionalline
> accept lastline
> r = createRecord(firstline, secondline, lastline, optionalline)
> return r
> recordlist = []
> for line in lines:
> recordlist.append(combineIntoRecord(line))
How about doing it this way?
class Acceptor:
def __init__(self, gen):
self.gen = gen
def next(self):
firstline = self.gen.next()
secondline = self.gen.next()
if condition(secondline):
optionalline = self.gen.next()
accept lastline
r = createRecord(firstline, secondline, lastline, optinalline)
return r
This is just a generator done longhand. If anything in Acceptor.next raises
StopIteration, so will Acceptor.next itself. Which means that you can now
write this:
for r in Acceptor(line):
recordlist.append(r)
or, for that matter,
recordlist = list(Acceptor(line))
Incidentally, I did not try to fix the bug in your code that if
condition(secondline) is false, optionalline never gets set so the program
will crash :-)
More information about the Python-list
mailing list