0

I have looked up a couple of solutions to this problem, but none of them seem to work. Lets just say I have a file named "Var", where I simply put:

myvar = 25
print("myvar is equivalent to 25.")

And then I have another file called "Run", where I put:

from Var import myvar
print(myvar)

From the "Run" file, the only thing I want to access from that file is the variable, but when I actually run the code, it runs the entire file, so the output is:

myvar is equivalent to 25.
25

All I want to do is access the variable but for some reason it is running the entire file! How do I get it so that it only gets the variable and doesn't run the entire file?

Yserbius
  • 1,375
  • 12
  • 18
  • A module should generally just define functions and variables, it shouldn't execute top-level code. – Barmar Jun 28 '21 at 23:14
  • 1
    Importing a script executes the script. – Barmar Jun 28 '21 at 23:15
  • 2
    You can't; importing **will** run the entire file. What you want is to **not** have any code in the file that's run in global scope, but instead just have everything defined in functions. That way, no code is run until you actually call the function. Or you want a [main guard](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Ted Klein Bergman Jun 28 '21 at 23:15
  • I just wanted to say that I'm so grateful for how fast you guys responded. Ya'll are life savers! – Zachary Menendez Jun 28 '21 at 23:19

1 Answers1

5

When a python module is loaded it will go through the file and execute all of the statements on the top level.

If you want the print statement to only happen if you execute the file as a script (say by running python Var.py) then you need to check if it is the "main" module.

To do so you can check the __name__ attribute.

For Var.py

myvar = 25


if __name__ == "__main__":
    print("myvar is equivalent to 25.")

For Run.py:

from Var import myvar


if __name__ == "__main__":
    print(myvar)
flakes
  • 21,558
  • 8
  • 41
  • 88