None weirdness

Erik Max Francis max at alcyone.com
Mon Dec 2 18:57:47 EST 2002


Ian McConnell wrote:

> Can someone explain what is going on here?
	...
> def main():
>     a = None
>     None = 1
	....
> UnboundLocalError: local variable 'None' referenced before assignment
> Exit 1
> 
> Python seems to be doing the 'None=1' assignment before 'a=None'!

The None is really a red herring here.  What you have is a classic case
where you're trying to refer to a global (None) but you haven't declared
it global.  Python has analyzed that local function (main), and
concluded that in it, None must be a local variable.  But then you try
to use its value (a = None) before it has one, so you get an
UnboundLocalError.  The solution would be to use a global statement at
the top of the function to hint to Python that you mean the global name
None, not a local one.

Not that reassigning None is _ever_ a good idea, anyway.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Nothing you have said / Is revelation
\__/ The Russian, _Chess_
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.



More information about the Python-list mailing list