[Tutor] strange variable problem
alan.gauld at blueyonder.co.uk
Sat May 22 03:14:07 EDT 2004
> > ftseptr is setup as a global variable, value -1,
> > yftseptr is setup as a global variable, value 0
> Ah! Common gotcha: when using global variables in functions, you
> to declare that the variable is 'global' in nature. For example:
Is that really the problem here?
He is not assigning to the variable merely printing it,
which shouldn't need the global keyword.
However I don't think we have the full story.
Looking at the traceback:
> Traceback (most recent call last):
> File "/home/dave/gg/gg.py", line 72, in -toplevel-
> File "/home/dave/gg/gg.py", line 62, in gg
> File "/home/dave/gg/gg.py", line 40, in file2datacore2
> File "/home/dave/gg/ggdatacore2.py", line 30, in add
> print ftseptr
> UnboundLocalError: local variable 'ftseptr' referenced before
we have calls to gg() and file2datacore2 and then add() for
which we have the code. Plus the program seems to be run from
a python prompt rather than being executed as a program.
If that is the case a lot depends on how the imports are being
done because that's when the global variables will be set up.
Presumably, for the code to get this far, the module gg does
But when is gg imported? Has anything changed between then
and the toplevel call to gg()?
What happens if you run your program outside the python prompt?
Does that change the error in any way?
> count = 0
> def makeNextName():
> global count
> nextName = "name%s" % count
> count = count + 1
> return nextName
> If the 'global count' declaration in the function is missing, then
> get the same UnboundLocalError that you're receiving in your
program, so I
> suspect the same thing is happening there.
Yes but in this case the error is because of the assignment which
tries to create a local variable. But Dave's code doesn't assign
to the variable merely prints it. So it should be OK,
unless he hasn't shown us the full code...
More information about the Tutor