1

I have two scripts in my current folder. From scriptMain.py I call scriptChild.py. In scriptMain.py I have already imported numpy. However, it seems that even though I call scriptChild.py by doing import scriptChild it still needs me to import numpy in the child script again.

Is this default behaviour in python, or is there a way to tell the child script to recognise all modules imported by the parent script?

If it helps I am using python 3.5.1 and spyder as my editor.

edit1:

Suppose further that in scriptChild.py I have that a=1. I need the variable a accessible through the parent as well. How do I make sure I do that. I tried running

import subprocess
subprocess.call("scriptChild.py", shell=True)

without any luck.

edit 2:

Found solution to edit 1 here: Importing a variable from one python script to another

Community
  • 1
  • 1
sachinruk
  • 9,571
  • 12
  • 55
  • 86

1 Answers1

1

The language that comes to mind with importing how you're talking about is C++. Python doesn't work like C++ when you use the #include directive. The #include directive actually tells the compiler to include the source code of whatever file you specify in the current source file. That's why you can grab the parent's inclusions. The compiler essentially fakes it out in source for you. I should add that this is why include guards are necessary (double includes will cause naming conflicts).

The import statement in Python, on the other hand, creates a reference to a module (it does not substitute in source). These references only allow you to access the "public" parts of a module, and doesn't automatically grab other imports for you. It's just the semantics of the import statement, neither inherently good or bad. I'm not saying there isn't a way around it, but this is certainly the intended and default behavior.

See here for more info about the #include directive and here for more info about import/from.

Community
  • 1
  • 1
Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52