Generators and co-routines

Jp Calderone exarkun at intarweb.us
Thu Mar 6 22:44:30 EST 2003


On Fri, Mar 07, 2003 at 11:32:47AM +0800, Simon Wittber (Maptek) wrote:
> Hello python people!
> 
> [snip]
> 
> The .poll() method checks if the user is logged in, if not, calls the
> .login() method (which is the co-routine/generator). My problem is the
> .login() method is not being called! I put a print statement at the
> start of the function, and nothing gets printed. I am entirely unfamilar
> with python generators, if someone can enlighten me, please do so!
> 
> ------<CODE>------
> 
> class User:
> 	def __init__(self, conn):
> 		self.conn = conn
> 		self.isLoggedIn = False
> 		
> 	def poll(self):
> 		if not self.isLoggedIn: 
> 			self.login()
> 

  This is your problem.  Generators must be iterated over.  If you change
"self.login()" to "for something in self.login()" you'll see some more
action, though this will probably have undesirable effects for the rest of
your program ;)

  An approach that might make sense is to return the generator from the
poll() method.  Then whatever is invoking the poll() method can collect
these generators and iterate them in some lockstep manner.  For example:

    def gameIteration(users, routines = {}):
        for user in users:
            if not routines.has_key(user.id):
                r = user.poll()
                if r:
                    routines[user.id] = r
        prune = []
        for user, routine in routines.iteritems():
            try:
                routine.next()
            except StopIteration:
                prune.append(user)
        for user in prune:
            del routines[user]

    def runGame():
        users = []
        ...
        while 1:
            gameIteration(users)

  Generators are iterators, so their "next" method causes them to be
resumed, and returns whatever value is yielded.  When the generator (or any
iterator) finishes, it raises StopIteration.  You may want to alter the
above to examine the return value of .next(), or allow more than one
generator at a time per user.

  Jp

-- 
 up 3 days, 19:58, 5 users, load average: 0.02, 0.01, 0.00





More information about the Python-list mailing list