name error
Gordon McMillan
gmcm at hypernet.com
Mon May 3 23:04:22 EDT 1999
Benjamin Derstine writes:
> test=line[0]
> location=line[0]
>
> def makeuser():
> mastlist=[]
> while test==location:
> list=f.readline()
> location=list[0]
> mastlist.append(list)
> makeuser()
>
> error:
>
> File "C:\WINNT\Profiles\bend\Desktop\licensing\loadtest.py", line
> 16, in makeuser
> while test==location:
> NameError: location
>
> It seems like I'm having a name space problem but there is nothing
> different between the test and the location variables when it comes
> to namespace.
Oh yes there is. Just not at all what you expect.
> Yet one works and the other doesn't. Anything I'm
> doing wrong?
makeuser assigns to location. In the absence of a "global" statement,
Python makes the assumption that location is a local (to makeuser).
So when it first hits " while test==location: ", it looks at the
(local) location, which has not been initialized. A "global location"
right after the def will tell Python to use the global var.
This is gotcha #3 - right after 1 / 2 == 0 and what happens when you
use a mutable object as a default.
- Gordon
More information about the Python-list
mailing list