Reputation: 23
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?
Upvotes: 0
Views: 1859
Reputation: 23624
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)
Upvotes: 5