1

Considering the following python code setup:

main.py
MTS/
    optimization.py
    __init__.py

Where __init__.py consists of one line import optimization and optimization.py uses different modules such as numpy (called as np). Let's main.py be:

from MTS import optimization
import numpy as np
a=np.load('data.npy')
b=optimization.minimize(a)

this code returns the following error:

global name 'np' is not defined

If I import numpy inside optimization.py, it works but I want to avoid importing the same module twice. How to share an imported module across other modules?

Yacine
  • 321
  • 2
  • 15

1 Answers1

2

In python, imports are mainly about namespaces. Importing a module puts it into the current namespace, and if it's not already in memory it loads it into memory.

If you import a module that another module has already imported, then that module is already in memory so you just get a reference to the existing module.

So, in other words, just do import numpy as np inside every file you need to use it in. This will not consume any extra memory, as numpy will only be properly loaded once, and every subsequent import statement will just add it to the namespace of whoever calls it.

An additional benefit of this is that it's much more clear that your code is going to use numpy - it would be confusing if you just used np.load() halfway through your program and there was no indication that you'd defined np anywhere (C has this problem, for example; pretty much every programming language since has used the idea of namespaces to avoid it, including even C++). It is poor practice in python to not do this.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53