Importing Numpy into functions Importing Numpy into functions numpy numpy

Importing Numpy into functions


As other answers say, you need to import numpy into each file where you call a Numpy function. However you don't need to import it into the main module if you're not using it in the main module. Here's a simple example. Imagine you have a file with your function in it called myFunc.pymyFunc.py:

import numpy as npdef f1(a):  # a is a numpy multidimensional array    z = np.array(a)    flat = z.ravel()    flat = flat.tolist()    return flat     

Then in your main file you can do something like this

import myFunc as mfmf.f1([[4,67,8],[7,9,7]])

Your output will be:

[4, 67, 8, 7, 9, 7]

So you pass a list to your function, convert it to a numpy array in your function, then return the answer as a list. If you return a numpy array you'll get an error.


You have to import modules in every file in which you use them. Does that answer your question?