[Tutor] bad name in module
Dave Angel
davea at davea.name
Fri May 10 11:50:02 CEST 2013
On 05/10/2013 01:45 AM, Jim Mooney wrote:
> I have a simple program, below, to create a specified list of random
> integers, which works fine.
> I saved it to Lib as makeRandomList.py, then imported it to a
> sorter.py program, like so. The import doesn't fail:
>
> import makeRandomList
>
> newRandomList = createRandomList()
>
> But I then get the following error:
>
> File "c:\Python33\Progs\sorter.py", line 3, in <module>
> builtins.NameError: name 'createRandomList' is not defined
>
> What am I doing wrong in creating the library module below, which
> works fine as a standalone?
>
The module is fine, but you need to understand better how to reference
it when importing.
The normal import statement makes a namespace, which contains all the
top-level symbols in the module.
So import makeRandomList
creates a new namespace makeRandomList, which contains in this case one
symbol. To call the function, you need to use that namespace:
newRandomList = makeRandomList.createRandomList()
Alternatively, if there are only a few symbols (one in this case) you
need from the imported namespace, you can name them in the other import
form:
from makeRandomList import createRandomList
Now you can just call createRandomList() directly.
These are the same rules you use when importing from somebody else's
library. So when you want to use the argv symbol from the sys library,
you can either do this:
import sys
and use sys.argv in your code. Or you can use
from sys import argv
and now you can use argv directly.
--
DaveA
More information about the Tutor
mailing list