1

I have two files, file1 and file2.

files 2 is this:

print "Why is this printing"

var = 7

file 1 is this:

from file2 import var

print var

When I run this code, it outputs the following:

Why is this printing
7

Is there a way I can obtain var from file2 without running the code above the declaration of var?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Keagan
  • 31
  • 1
  • 4

2 Answers2

2

If you don't want code to run when a module is imported, put it in a function:

def question():
    print("Why is this printing")

If you want the function to run when the module is passed to the python interpreter on the command line, put it in a conditional expression block:

if __name__ == '__main__':
    question()

e.g.

c:/> python file2.py
Why is this printing
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • I see. Thanks! I am wondering: Why does the answer given here http://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it use that 'main' function - it looks like it doesn't do anything. – Keagan Mar 18 '17 at 23:04
  • It's an example. If you want the program to do something, replace `pass` with the actual code. – Peter Wood Mar 18 '17 at 23:06
0

You can use standard

if __name__ == "__main__":

guard to protect some lines from executing on importing. This condition is satisfied only if you run that particular file, not import it.

Ilya V. Schurov
  • 7,687
  • 2
  • 40
  • 78