Generators and co-routines

Simon Wittber (Maptek) Simon.Wittber at
Fri Mar 7 04:32:47 CET 2003

Hello python people!

I am rewriting the User class for my mud system, and am trying to use a
generator function to simulate a co-routine, which helps me maintain
state much more elegantly than the previous while loop with humungous
amounts of if / elif statements.

I have a server class, which loops through all connected users, calling
the .poll() method.

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!


class User:
	def __init__(self, conn):
		self.conn = conn
		self.isLoggedIn = False
	def poll(self):
		if not self.isLoggedIn: 

	def login(self):
		print "in .login()"
		sentUserRequest = False
		sentPassRequest = False
		recvUser = False
		recvPass = False
		if not sentUserRequest:
			self.conn.send("username: ")
			yield False
		while not recvUser:
			if len(self.conn.lines) > 0: 
				username = self.conn.lines.pop(0)
				recvUser = True
				yield False
		if not sentPassRequest:
			self.conn.send("password: ")
			yield False
		while not recvPass:
			if len(self.conn.lines) > 0: 
				password = self.conn.lines.pop(0)
				recvPass = True
				print username, password
				yield True

More information about the Python-list mailing list