None weirdness

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Dec 2 09:32:38 EST 2002


On 02 Dec 2002 12:42:30 +0000, Ian McConnell <ian at infosar.co.uk> wrote:

>Can someone explain what is going on here?
>
>
>#!/usr/bin/python2.2
>
>def main():
>    a = None
>    None = 1
>

Do *not* use None as a name. It is a sure way to shoot yourself - and I
believe None will be made into a keyword somewhere in the future.

>if __name__ == "__main__":
>    main()
>
>
>Traceback (most recent call last):
>  File "sub.py", line 8, in ?
>    main()
>  File "sub.py", line 4, in main
>    a = None
>UnboundLocalError: local variable 'None' referenced before assignment
>Exit 1
>
>
>
>Python seems to be doing the 'None=1' assignment before 'a=None'!

Python has to decide which names are local and which ones are global. In
order to be able to make some optimizations it scans the *whole*
function block to look up assignments and on that basis, decide which
names are local.

If you want to make a name global and be able to rebind it add an
explicit declaration:

global <name>

>
>
>If this seems like pretty weird code, then it resulted from me trying to do
>        a, None = func()
>
>func() returns a pair of answers, but I was only interested in the first, so
>I thought that "a, None" would just drop the second value. However, it
>redefined None. 

Of course. None is not a keyword so you can (still) rebind it. 

>
>I now use
>        a, = func()
>which works, but doesn't seem as clear to me.


Why not

a = func()[0]

This is the Pythonic way.

HTH,
G. Rodrigues



More information about the Python-list mailing list