Unexpected global variable behaviour

Fredrik Lundh fredrik at pythonware.com
Mon Aug 25 16:41:49 EDT 2008


RgeeK wrote:

> I'm seeing something which make me think I'm missing something  about 
> how global var's behave.  I've defined a global string, right at the 
> start of my .py file.
> 
> outXMLfile = "abc"
> 
> I define a class and do a bunch of stuff below that.  Then I have 
> another class, and in it, there is a method 'def' that has:
> 
>   def OnOutfileButton(self,evt):
>    (fPath, fName)=os.path.split(fullName)
>     print "Selected output file: " + fName
>     outXMLfile = fName
> 
>     print "output file: " + outXMLfile
> 
> Print statements in random other places in the project, show outXMLfile 
> prints as "abc"  however, in this def, it comes out as the same as fName 
> (e.g. "myfile.xml")   If the print line for outXMLfile is before the 
> assignment to fName, it throws the error:
> 
>  UnboundLocalError: local variable 'outXMLfile' referenced before 
> assignment
> 
> If I remove the line that says "outXMLfile = fName"
> then the print statement gives me the value "abc"
> 
> What am I missing?  When I assign a value to update my global variable, 
> it becomes a local variable. If I don't try to update it, it stays 
> global.  I assume it's acting like a constant, though I have a couple of 
> global lists and I seem to be able to append to them okay.

http://docs.python.org/ref/naming.html

"If a name binding operation occurs anywhere within a code block, all 
uses of the name within the block are treated as references to the 
current block. This can lead to errors when a name is used within a 
block before it is bound."

to fix this, use the global directive:

http://docs.python.org/ref/global.html

    def OnOutfileButton(self,evt):
      global outXMLfile # flag variable as global
      fPath, fName = os.path.split(fullName)
      print "Selected output file:", fName
      outXMLfile = fName
      ...

</F>




More information about the Python-list mailing list