Mystery of module bindings!
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Apr 29 15:49:14 EDT 2013
On Mon, 29 Apr 2013 12:30:29 -0700, Peter Rowat wrote:
> This must be a trivial question:
>
> I have "import numpy as np" in the python startup file.
That only runs interactively. It does not run when you execute a script.
> 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 ? =======
Let's suppose it was. What would that mean?
Look inside mod1, where there might be a function spam(), and also
another function eggs(). spam() calls eggs(), it sees the eggs function
in the same module, and all is well with the world.
Then you add to the startup file:
def eggs():
return "Something unexpected"
and all of a sudden mod1.spam() breaks, because it now sees *your* eggs()
instead of its eggs. This would be a bad, bad thing.
This is why modules are their own namespace, and the interactive
interpreter is its own, independent, namespace. What happens in the
interactive interpreter stays in the interactive interpreter, without
stomping all over every other 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?
The point of the startup file is to add things to the interactive
interpreter's module, not to inject things into every module in sight.
--
Steven
More information about the Python-list
mailing list