[Tutor] Declaring a global variable (where?)

Abel Daniel abli@freemail.hu
Mon Jun 30 13:35:02 2003


Vicki Stanfield wrote:
> I am trying to declare a file handler as a global so that I can access
> from within any of my def blocks. I tried to add "global outfile" after
> the include statements at the beginning of the program and then use the
> same name in the assignement statement:
> 
> Class myClass:
>     def __init__(self, parent, ID = -1, size = wxDefaultSize, style= -1):
> [snip]
> 	self.outputfilesel = wxFileDialog(self, message="Choose output file.",
>         defaultDir = "C:/",wildcard = "*.log", )
>         self.outputfilesel.ShowModal()
>         self.outputfilesel.Destroy()
>         logfile = self.outputfilesel.GetFilename()
>         outfile = open('C:/' +logfile, 'w')
> [snip]
> 
> But I get a NameError: global name 'outfile' is not defined. Is this the
> appropriate place to place a global declaration?
The code you posted doesn't show the problem so I'm not sure, but I think
you aren't using global right.

You should be using global in the method where you are assigning to the
global variable.

I think you are doing:
>>> global a
>>> def f():
...     a=1
... 
>>> a=0
>>> f()
>>> print a
0

Instead of:
>>> def g():
...     global b
...     b=1
... 
>>> b=0
>>> g()
>>> print b
1

Notice that in the first example, calling f() didn't have any effect. a
was declared global outside, but _not_ in the scope of f(). So inside f,
a new 'a' was created and bound to the number '1'. But that didn't have
any effect on the 'a' in the outside scope. (Because the new name masked
the 'a' in the outside scope.)
You should put the global statement where you are rebinding that name,
in this example in myClass.__init__

(You get the NameError because you don't bind anything to the global outfile
as the one you do bind (assign) to is in myClass.__init__'s local scope,
which disappears when that method finishes. So when you try to use it, it's
not found.)

Abel Daniel
p.s. Insert standard disclamer on the evils of global variables...