Reputation: 16275
I have the following lines at the beginning of my script:
global lotRow
global lotCol
Then, later on, I set lotRow and lotCol as strings using a function. Then, even later, I do the following:
getIDFromAxes(int(lotRow), int(lotCol))
This gives me:
getIDFromAxes(str(lotRow), str(lotCol))
NameError: global name 'lotRow' is not defined
I have the def() print the "lot" strings at the end to be sure they are set, and I still can't access them for some reason.
Upvotes: 0
Views: 90
Reputation: 63797
You'll need to use the keyword global
when inside the function that is trying to access your global variables, otherwise it will look for a local definition - which of course doesn't exist.
global global_variable
def set_var ():
global global_variable
global_variable = 3
def print_var ():
global global_variable
print int(global_variable)
set_var ()
print_var ()
global_variable = 321
print_var ()
output:
3
321
Upvotes: 2
Reputation: 129001
global
statements don't go at the beginning of a script; they go inside of a function that needs access to global variables. So rather than:
global x
x = 0
def increment_x():
x += 1
return x
You'll need to use:
x = 0
def increment_x():
global x
x += 1
return x
Upvotes: 4