0

I have read all of the answers of the following link : Importing variables from another file? I have tried what they say, to import my variables from one file to another by tapping :

from file1 import *

or

from file1 import var1

Unfortunately it does not work as intented because I am not importing the variable only but the whole file1. That is not the purpose (I really only want var1, the script is rather big) so I am wondering if I am the only one noticing this behaviour as everybody there looks satisfied with the answer.

Thanks for your help.

  • 3
    `from file1 import var1` is better code, but any approach you use will _always_ import the whole module so there are no savings to be made – roganjosh Oct 22 '19 at 08:24
  • Python is interpreted and it has no way of finding out where `var1` is in the file, which is why it has to run the entire code and then import `var1`. – Diptangsu Goswami Oct 22 '19 at 08:28
  • @roganjosh Is correct. See [here](https://softwareengineering.stackexchange.com/questions/187403/import-module-vs-from-module-import-function) for a better explanation. – RightmireM Oct 22 '19 at 08:29

1 Answers1

1

You most likely have some code running in your file which is either outside of defined functions all together or in a main function that is run automaticalls upon running (and thus also when imported.

In other words if file1 looks like this:

var1 = 'hello'

def printHello():
    print var1

then writing from file1 import var1 will only import that. If on the other hand file1 looks like this:

var1 = 'hello'

print var1

It will import var1 but also print 'hello'.

S. L.
  • 630
  • 8
  • 19