[EMAIL PROTECTED] 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.
>
> I've been through the modules section of Python docs and a few ebooks
> as well, all suggest that it shouldn't be working this way.
>
> Please help out ppl.
>   

It's a scoping problem. The line

_exitcode = 0

creates a (module level) global object.

But in 

def setExitCode():
    _exitcode = 1

you are running into Python's default presumption that variables assigned to in 
a function are *local* to that function.  And like all local variables, they 
can be set and used within the function, but are independent of objects outside 
the function.

If you want to assign to a global object from within a function, then you must 
explicitly say so:

def setExitCode():
    global _exitcode
    _exitcode = 1

See: http://docs.python.org/ref/global.html 

Gary Herron


> Thanks
>
>   

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to