Module variables

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed May 28 12:36:12 EDT 2003


"Cameron Zemek" <grom_3 at optusnet.com.au> wrote in 
news:3ed4e018$1 at usenet.per.paradox.net.au:

> Okay I have been translating some pascal into python. I need to have
> variables with module scope. atm I'm doing this with "global" in methods
> that need to update the global variable. Is there a way todo this that
> doesn't need each function to declare what global variables it will need.

Turn the functions that access the global variables into methods in a 
class, then just refer to the variables through self.

You can create a module level variable that instatiates the class once.

e.g.

class InputHandler:
    def GetChar(self):
        try:
            self.Look = self.input[self.index]
            self.index += 1
        except IndexError: # Don't use a bare 'except'
            self.Look = '\n'

    def Match(self, char):
        if self.Look == char:
            self.GetChar()
        else:
            Expected("'" + str(char) + "'")

etc.

> Also what is the naming convention for variables and functions that are
> internal to the module?

Whatever you like, but a single underscore preceding variables that are 
supposed to be internal is common.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list