Nastiness with global vars. How do I avoid?

Rich Daley rich at DELETE_THISowl.me.uk
Wed Nov 27 16:03:24 EST 2002


Hi all.

I attach the beginnings of a piece of code which will become an ewtoo
<http://www.ewtoo.org> style chat room.

However, at the moment I use a global dictionary to hold the users' names,
and I realise that as the code gets bigger and longer (and more Object
Oriented) it's going to be harder and harder to maintain it this way.

Does anyone have any idea how I could use a Class instead to acheive the
same functionality? Ideally I'd love to have classes for all the different
kinds of methods and stuff too, but this is the most critical bit.

I'm not sure I made sense, so please ask me if this doesn't make sense...

Thanks in advance for your help!

~ Rich


------BEGIN CODE main.py------
#!/usr/bin/python
import SocketServer,socket,string,time

users = {}

class TalkRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        global users
        self.user_connect()
        stillhere = 1
        while 1:
            if not stillhere: break
            msg = self.request.recv(1024)
            if not msg: break
            stillhere = self.process(msg)
        self.user_disconnect()
        
    def user_connect(self):
        global users
        self.send_user_unterminated('Enter your name: ')
        name = self.request.recv(1024)
        self.name = name.strip()
        if not self.name.isalpha():
            self.send_user('Sorry, name must be only letters')
            return
        if users.has_key(self.name):
            self.send_user('Sorry, name in use')
            return
        self.send_all('+++ '+self.name+' connected!')
        users[self.name] = self.request
        self.look()

    def user_disconnect(self):
        global users
        del(users[self.name])
        self.send_all('--- '+self.name+' disconnected!')

    def send_user(self,msg):
        self.request.send(msg + '\n')

    def send_user_unterminated(self,msg):
        self.request.send(msg)

    def send_all(self,msg):
        for user in users:
            users[user].send(msg + '\n')

    def process(self,msg):
        command = ""
        args = ""
        if msg[0].isalpha():
            command_completed = 0
            for char in msg:
                if (not command_completed):
                    if char.isalpha(): command += char
                    else:
                        command_completed = 1
                        args += char
                else: args += char
        else:
            command_completed = 0
            for char in msg:
                if (not command_completed):
                    if char.isalpha() or char.isspace():
                        command_completed = 1
                        args += char
                    else: command += char
                else: args += char
        
        command = command.strip().lower()
        args = args.strip()

        #self.send_user("Command: "+ command+" Args: "+args)
                    
        if command == "'" or command == '"' or command == 'say':
            self.say(args)
        elif command == ';' or command == ':' or command == 'emote':
            self.send_all(self.name+" "+args)
        elif command == '~' or command == 'think':
            self.send_all(self.name+" thinks . o O ( "+args+ " )")
        elif command == ')' or command == 'sing':
            self.send_all(self.name+" sings o/~ "+args+" o/~")
        elif command == 'hug':
            self.hug(args)
        elif command == 'who':
            self.who()
        elif command == 'look':
            self.look()
        elif command == 'quit':
            self.send_user('Thanks for visiting! Come back soon!')
            return 0
        else: self.send_user("I don't know how to "+command+
                             ". I'm sorry but I'm very primitive.")
        return 1

    def look(self):
        global users
        lookstr = "Welcome to Talk! This talker is in very early stages\n"
        lookstr += "of development, and as a result it's pretty crap.\n"
        lookstr += "Please, take a look around though :)\n\n"
        if len(users) == 1:
            lookstr += "You're on your own here :(\n"
        else:
            i = 0
            userstr = ""
            for user in users:
                if user != self.name:
                    i += 1
                    userstr += user + "\n"
            lookstr += "You are here with the following " + `i` + " people:\n"
            lookstr += userstr
        self.send_user(lookstr)

    def who(self):
        global users
        whostring = "---WHO---\n"
        for user in users:
            whostring += user + "\n"
        whostring += "---------"
        self.send_user(whostring)

    def say(self,line):
        if line.endswith('?'):
            self.send_all(self.name+" asks '"+ line + "'")
        elif line.endswith('!'):
            self.send_all(self.name+" exclaims '"+ line + "'")
        else:
            self.send_all(self.name+" says '"+ line + "'")

    def hug(self,user):
        global users
        if user.lower() in map(string.lower,users.keys()):
            self.send_all("* "+self.name+" extends arms and hugs "+user)
        else: self.send_user("No user called "+user+" logged in")

class TalkServer (SocketServer.ThreadingTCPServer):
    pass

addr = ('0.0.0.0', 4321)

TalkServer.allow_reuse_address = 1

server = TalkServer(addr, TalkRequestHandler)

server.serve_forever()
------END CODE main.py------

--
 ___
{o,o}	~ Rich		<http://www.owlsound.co.uk/me/>
/)  )			rich at owl.me.uk
-"-"-			ICQ# 60415679 | Jabber: owl at jabber.spodzone.org.uk




More information about the Python-list mailing list