WilliamM
05-31-2008, 12:46 PM
In traditional (compiled procedural) languages, you would usually declare a global variable at the top-level, and then use it throughout functions/procedures as you would a local variable without declaring it again. Within each function there is no indication that the variable is global because those are the scoping rules of the language: if you define a variable outside of a function, it's global.
Python is different. A variable declared as global (even at the top-level) can be "read" without difficulty, but you can't "write" to it without first telling Python that you wish to do so (by using the global statement again within the function). Forgetting to do so results in the creation of a similarly named local variable, with no relation to the intended global variable. Thus, putting "global variableName" within a function can be though of as telling Python it's ok to change the variable.
global x #redundant 'top-level' declaration
x = 1
def read_x():
return x #references global variable x
def wont_modify_global_x():
x = 2 #creates a local variable called x
def will_modify_global_x():
global x #makes global variable x locally accessible for modifying
x = 2 #modifies global variable x
Python is different. A variable declared as global (even at the top-level) can be "read" without difficulty, but you can't "write" to it without first telling Python that you wish to do so (by using the global statement again within the function). Forgetting to do so results in the creation of a similarly named local variable, with no relation to the intended global variable. Thus, putting "global variableName" within a function can be though of as telling Python it's ok to change the variable.
global x #redundant 'top-level' declaration
x = 1
def read_x():
return x #references global variable x
def wont_modify_global_x():
x = 2 #creates a local variable called x
def will_modify_global_x():
global x #makes global variable x locally accessible for modifying
x = 2 #modifies global variable x