Co-routines

Sean Ross frobozz_electric at hotmail.com
Thu Jul 17 11:11:25 EDT 2003


Actually, that last bit of code wasn't quite right, since it relied on the
LockStepper's to control the alternating between each others statement
execution. What is probably being asked for is something outside the
LockStepper's that will manage the switching.

class LockStepper:
    def __init__(self, id, nstmts):
        self.id = id
        self.stmt = 1
        self.nstmts = nstmts

    def next(self):
        print "instruction %s-%s"%(self.id, self.stmt)
        self.stmt += 1

    def hasnext(self):
        return self.stmt <= self.nstmts

class Switcher:
    def __init__(self, *steppers):
        self.steppers = steppers
    def __call__(self):
        while True:
            for stepper in self.steppers:
                if stepper.hasnext():
                    stepper.next()
            if self._done():
                break
    def _done(self):
        return not [f for f in (f1,f2) if f.hasnext()]


f1 = LockStepper(1, 4)
f2 = LockStepper(2, 7)
switch = Switcher(f1,f2)
switch()






More information about the Python-list mailing list