-1

I have a file called test1.py with the following code:

print("HELLO WORLD")
x=999

I have another file called test2.py with the following code:

from test1 import x

print(x,"hello!")

Why is this the output:

HELLO WORLD
999 hello!

Why does it perform the function in test1 instead of just getting me the variable x?

In test.py I have tried:

from test1 import x as a
print(a,"hello!")

This gets me the same output.

Expected result:

999 hello!

Actual result:

HELLO WORLD
999 hello!

Sorry if this was a repeated question - I just can't find a solution. EDIT: This was marked as a duplicate earlier - one problem with that: using if __name__ == "__main__" logic prevents me from accessing any variable in main. I just want a variable without running the file.

SiHa
  • 7,830
  • 13
  • 34
  • 43
arpanet101
  • 183
  • 1
  • 11
  • Can we see more of your code, how did you import it? – EcSync Jul 03 '19 at 06:33
  • That is all the code - I didn't do anything fancy here, I just want to get the value for x into test2.py without running the code in test1.py – arpanet101 Jul 03 '19 at 07:08
  • 1
    in test1.py you should have `x` in a separate function. Then importing `x` would look something like `from test1 import function`. Write the function so it returns `x`. `x` will now be an attribute of test1 – EcSync Jul 03 '19 at 07:11
  • 1
    Yes that solved it - thanks! – arpanet101 Jul 03 '19 at 08:12

1 Answers1

1

modules are executed on import. If the modules contains code you dont want to be executed on import you can wrap this code with an if-block ìf __name__ == "__main__".

http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm (found in Why is Python running my module when I import it, and how do I stop it? )

Raphael
  • 1,731
  • 2
  • 7
  • 23