4

I do not know the right way to import modules.

I have a main file which initializes the code, does some preliminary calculations etc. I also have 5 functions f1, f2, ... f5. The main code and all functions need Numpy.

If I define all functions in the main file, the code runs fine. (Importing with : import numpy as np)

If I put the functions in a separate file, I get an error:
Error : Global name 'linalg' is not defined.

What is the right way to import modules such that the functions f1 - f5 can access the Numpy functionality?

1
  • import numpy at the beginning of every file, if it's been imported once, it won't import again, but you will have the namespace to work with. Commented Aug 3, 2012 at 3:42

2 Answers 2

5

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.py myFunc.py:

import numpy as np

def 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 mf

mf.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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Yes. I thought that was repetitious and the right way was to just import them once. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.