Reputation: 24748
I have this simple python script where myvar1
is accessible in generate()
function but not in copy()
function. Need help figuring out the error:
#!/usr/bin/python
import os, time
def Test(tcid,descr,iterations,filsz):
def setup():
print "entering set up\n"
global myvar1, myvar2
myvar1 = 1.0
myvar2 = os.getcwd()
def generate():
print "entering generate\n"
print "in generate", myvar1, myvar2
def copy():
print "in copy", myvar1, myvar2
myvar1 += 5.0
setup()
generate()
for loopcount in range(5):
loopcount = loopcount + 1
copy()
if __name__ == "__main__":
Test('test','simple test',2,10)
Error:
Traceback (most recent call last): File "./pyerror.py", line 35, in Test('test','simple test',2,10) File "./pyerror.py", line 30, in Test copy() File "./pyerror.py", line 20, in copy print "in copy", myvar1, myvar2 UnboundLocalError: local variable 'myvar1' referenced before assignment
Upvotes: 1
Views: 176
Reputation: 107588
You need global
wherever you overwrite a global in a function. setup
set myvar1
as a global but you used it as a unset local variable. Hence the "local variable 'myvar1' referenced before assignment"
def copy():
global myvar1
print "in copy", myvar1, myvar2
myvar1 += 5.0
If you're reading a tutorial that suggests using global
regularly then throw it away, burn it and start with a different one.
Upvotes: 2
Reputation: 601401
In the copy()
function, myvar1
is not declared as global, but assigned to in the statement myvar1 += 5.0
. This implicitly makes the myvar1
a local variable. The print statement in the first line of the function also tries to access a local variable with the name myvar1
, but such a local variable does not exist yet.
Local variables are determined statically, i.e. at compile time. When the copy()
is compiled by Python, myvar1
is marked as local variable for the whole function body. It may be instructive to look at the easiest code to trigger this error:
def f():
print x
x = 5
x = 3
f()
Upvotes: 2