Saturday, August 1, 2009

Python: Global variable funda and a real mess


Share at Facebook

For any new python coder, its a pain, if you are not aware about local and global reference. Its not other scripting language, that if you change it locally, and it will be effected at global. Not at all. You have to tell you python about that.

Here is an example.

## a global variable
my_global_var = 10

def set_global(val):
## changing global variable
my_global_var = val
print "After Change ", my_global_var

## Tesing
set_global(5)
print "Finally ", my_global_var


At this example, you can see that the global variable is changed inside the function set_global(), but the output of the script is not telling this is true. Its output should show 5 both cases. Instead, it is displaying
After Change  5
Finally 10


Why? It will be your question, if you are a new coder at python world. To use a global variable at locally, you have to use global like PHP before the variable inside the local scope. So the correct code will be.
## a global variable
my_global_var = 10

def set_global(val):
## using global variable at local scope
global my_global_var

## changing global variable
my_global_var = val
print "After Change ", my_global_var

## Tesing
set_global(5)
print "Finally ", my_global_var


It will now display the 5 for both cases.
After Change  5
Finally 5




No comments: