Python - Importing packages by running a script

Viewed 37

I have a script which is importing lots of packages, including import numpy as np.

I have lots of scripts which need to import all of these packages (including some of my own). To make my life easier, I have a file called mysetup.py in my path to import all the packages. It includes the statement in a function called "import numpy as np".

I run "main.py". It runs the following

from mysetup import *
import_my_stuff()
np.pi()

"mysetup.py"

def import_my_stuff(): 
   import numpy as np
return 

However, I am unable to use numpy in "main.py" - this code will fail. Any suggestions as to why?

2 Answers

The problem you are facing is a consequence of a very important features of Python: namespaces.

Basically, in your case, when you do that (numpy) import inside the (import_my_stuff) function, you are defining the code object numpy/np inside the function namespace. (scope, if you prefer).

To solve your issue (the way you are doing; not the only way), you should simply import everything at the module top level (without a function encapsulating the imports):

mysetup.py:

import numpy as np
# other modules... 

main.py:

from mysetup import *
np.pi()

Imports in functions are not the best idea. But you can just define whatever imports you need in top level code of mysetup.py

import numpy as np

and then it will be available when you import * from mysetup

from mysetup import *
print(np.pi)
Related