Python globals

Posted by Martijn on Tue 23 Oct 2007 12:06 PM — 6 posts, 27,139 views.

#0
This doesn't work:


empties = 0

def addempty(theName, theOutput, wildcards):
  global empties += 1



It's probably a problem with globals in Python, and the way MUSHclient calls python scripts, but I can't think of a way around it, apart from using a 'Global Mushclient variable'.

It's part of a plugin, and I would like to keep it contained in the plugin, and not muck around with world variables. If I have no choise however, I have no choise, but I guessed someone may have found a way around it. If anyone could lend a hand, I would be most gratefull. If you need more information on the plugin, just ask, and I'll post the rest.
Russia #1
Change it to:


empties = 0

def addempty(theName, theOutput, wildcards):
  global empties 
  empties += 1
#2
yup, thanks. I always muck up my Python globals.
#3
I mess these up, too, and always forget to type 'global variable' in my script function.

I've started just writing all the code out, and then going back through and typing all the globals out when I'm done.
Netherlands #4
For future reference, it might help to consider the global keyword as a declaration. "The variable with the name empties is considered global and will be treated as if we were in the global scope." Notice how it doesn't say anything about the current value or the new values it may get in the function. :)
#5
NOTE: I posted this in another topic regarding Global Variables

-----
It was recommended in a python manual to create a class 
that holds global variables. Here is an example that I 
culled from a script I wrote to work with the mailman 
software package:

class GlobalVariables:
    'Class that holds Global Variables'
    def __init__(self):
        self.LDIR = '/var/lib/mailman/lists'
        self.BDIR = '/usr/lib/mailman/bin'
        self.THLD = ''
        self.MLST = ''
        self.EOJ = 0


Then, in the main(), create a varaible using this class:

def main():
    global GL
    GL = GlobalVariables()
    input_list()
    process_list()


In any other subroutine that would need access to the 
Global Variables, just include the global statement. The 
following code is a very simplified version from my script:

def input_list():
    global GL
    GL.MLST = raw_input("Enter Mailing List: ")

def process_list():
    global GL
    cfgfile = '/tmp/'+GL.MLST+'_config'
    regfile = '/tmp/'+GL.MLST+'_member'
    digfile = '/tmp/'+GL.MLST+'_digest'


As you can see, it is much easier to remember the "global GL" 
in each routine rather than multiple "global" statements!