N00b question on Py modules

Christoph Haas email at christoph-haas.de
Mon May 7 03:13:06 EDT 2007


On Mon, May 07, 2007 at 12:00:38AM -0700, lokesh.jagasia at gmail.com wrote:
> Hi. Sorry to sound like a noob but that's what I am when it comes to
> Python. I just wrote the below module and it behaves funny.
> 
> My python module:
> 
> _exitcode = 0
> 
> def setExitCode():
>     _exitcode = 1
> 
> if __name__ == '__main__':
>     print _exitcode
>     setExitCode()
>     print _exitcode
> 
> Actual O/P:
> 0
> 0
> 
> I expected to see an output of 0 followed by 1. But it turns out that
> the _exitcode variable is not changed at all. It seems that
> setExitCode() might be editing a local copy of the _exitcode variable.
> But then, how do I tell it to change the value of the module variable
> and not its local variable.

_exitcode is a global variable in your program. In functions (def) you
can read global variables. But if you change or reassign them the change
will be only local to the function. If you want to change the global
variable your def needs to be:

def setExitCode():
    global _exitcode
    _exitcode = 1

Kindly
 Christoph




More information about the Python-list mailing list