Why don't my global variables work?
Gordon McMillan
gmcm at hypernet.com
Thu Jun 17 12:56:25 EDT 1999
Nathan J Froyd writes:
> Can somebody explain this point to me? I have the following program
> Could somebody look at this, perhaps running the program and explain
> to me what fundamental fact I am missing here? Because it looks like
> my program should run without errors. Thanks!
/snip/
> # I HAVE DEFINED `count' HERE, PYTHON!
> count = 0
/snip/
> def topic_read(regmatch, evilcount):
> # if you comment this line, the program will not work
> count = evilcount
> print "\t" * count, "<topic name=\"%s\">" % regmatch.group(1)
> count = count + 1
Alas, the FAQ is down, so I can't point you there.
Changing the binding of a global var requires a "global" statment.
def topic_read(...):
global count
count = count + 1
Without that, Python (at the time the "def" is scanned) decides you
are creating a local var named count. Then you go and reference said
local var before you've given it a value. Boom. NameError.
Non-intuitive, perhaps, but think of the strange bugs you'd have if
locals didn't shadow globals of the same name.
- Gordon
More information about the Python-list
mailing list