Mystery of module bindings!

P

Peter Rowat

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:
..... (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?

-- PeterR
 
S

Steven D'Aprano

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:
.... (numpy imported as np)


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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top