Global variables?

Peter Hansen peter at engcorp.com
Thu Jun 24 14:59:49 EDT 2004


RiGGa wrote:

> I am having problems getting my script to recognize global variables ...
> 
> global myvariable
> myvariable = 0
> 
> class MyHTMLParser(HTMLParser):
>         def handle_data(self, data):
>                 if myvariable == 1:
>                         'Do some more stuff here'
> 
> 
> 
> if __name__ == "__main__":
      [snip code]

> What am I doing wrong?? (Im a Python newbie so be gentle!)

"global" is only meaningful *inside* a function, not at
the module level where you have it.  In fact, you have to
specify it in *each* function in which you intend to modify
the global variable.

Basically, if you use a variable name in a function and you
haven't said it's global, Python assumes it's local *if* you
are writing to it (or "rebinding the name", which is more
correct and quite different in some cases, but basically the
same thing for simple variables as you are using above).

For more, and for many other things you should read about,
see the FAQ, especially the following entry:
http://www.python.org/doc/faq/programming.html#how-do-you-set-a-global-variable-in-a-function

(That's all one line, in case it gets split up.)

-Peter



More information about the Python-list mailing list