Reputation: 321
I created a module which is going to be used in several python scripts. The structure is as follows:
Main file:
import numpy as np
from mymodule import newfunction
f = np.arange(100,200,1)
a = np.zeros(np.shape(f))
c = newfunction(f)
mymodule.py:
def newfunction(f):
import numpy as np
b = np.zeros(np.shape(f))
return b
if __name__ == "__main__":
import numpy as np
Don't mind the functionality of this program, but the problem is that when I run it, I get "NameError: global name 'zeros' is not defined".
What am I missing out on here?
Upvotes: 3
Views: 5109
Reputation: 16346
mymodule.py doesn't see:
import numpy as np
statement(s). "import" statement in Python doesn't work like #include in C++, it merely creates new dictionary of objects contained in imported module. If you want to use 'np' identifier within that dictionary, you have to explicitly import it there.
Regarding
if __name__ == "__main__":
import numpy as np
-- this is only called when you execute mymodule.py as standalone script, which probably is not the case in this question.
EDIT:
OP changed sample code, by adding import numpy as np
inside his function, and my answer is for the original question.
Upvotes: 3