Why don't my global variables work?
gmcm at hypernet.com
Thu Jun 17 18:56:25 CEST 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!
> # I HAVE DEFINED `count' HERE, PYTHON!
> count = 0
> 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.
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.
More information about the Python-list