Module variables

Gerhard Häring gh at ghaering.de
Wed May 28 12:42:32 EDT 2003


Cameron Zemek wrote:
> Okay I have been translating some pascal into python. 

I'll not comment on this code for now (perhaps later) and try to answer 
your immediate question only.

> I need to have variables with module scope. atm I'm doing this with "global" in methods
> that need to update the global variable.

You're correct: you only need "global" when you *update* a variable. For 
read-access, you don't need a global declaration in a function.

> Is there a way todo this that doesn't need each function to declare
> what global variables it will need. 

Sure. Just declare them in module-scope:

#v+
username = None

def get_username():
     global username
     username = raw_input("What's your name? ")

def greet():
     print "Hello, %s!" % username

if __name__ == "__main__":
     get_username()
     greet()
#v-

I always initialize "undefined" variables with None.

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

The Python convention is to not use globals, unless really necessary ;-) 
Other than that, there is no naming convention. Except that if they're 
constant, you use all-uppercase names, like:

MAX_WRONG_PASSWORD_ENTRIES = 3

-- Gerhard






More information about the Python-list mailing list