Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Importing packages by running a script

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading