views:

61

answers:

1

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?

+3  A: 

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.

Tomasz Zielinski
I have tried this, but still the same error.
mymodule.py works perfect as a standalone script, but when I call it from the main .py-file I get the "global name .. not defined" error.
I tried it too, and it works for me!
EOL
@williamx - if you ran it as standalone script, then numpy is imported as np, so everything works like a charm. But when you import mymoduly.py to main .py file, numpy is not imported!
Tomasz Zielinski