Mystery of module bindings!

Ethan Furman ethan at stoneleaf.us
Mon Apr 29 15:53:32 EDT 2013


On 04/29/2013 12:30 PM, Peter Rowat wrote:
> This must be a trivial question:
>
> I have "import numpy as np" in the python startup file.
>
> A file called mod1.py contains "def myfn..."
>   and inside myfn there is a call to, say, "np.convolve".
>
> Interactively:
>> python
> .... (numpy imported as np)
>
>> import mod1
>>
>> mod1.myfn(...)
>
> Error: global name "np" is not known.
> =======
> Why is "np" not known to functions in an imported module ?
> =======
>
> I can fix this by including "import numpy as np" in any module that uses numpy
> functions -- but then what is the point of having a startup file?

That "fix" is indeed the way things are done.  Modules only know about what they import or create*.

The point of the startup file is to have things ready for interactive investigation -- if you use numpy *alot* then 
having it already there beats the heck out of typing `import numpy as np` every time you start the interpreter.

--
~Ethan~

*Unless you start playing with injection and stuff.



More information about the Python-list mailing list