Why is Python running my module when I import it, and how do I stop it?

Dasmowenator picture Dasmowenator · Jun 29, 2011 · Viewed 162.2k times · Source

I have a Python program I'm building that can be run in either of 2 ways: the first is to call "python main.py" which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call "python batch.py -file-" which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.

The problem is that when I run "batch.py" it imports some variables/methods/etc from "main.py", and when it runs this code:

import main

at the first line of the program, it immediately errors because it tries to run the code in "main.py".

How can I stop Python from running the code contained in the "main" module which I'm importing?

Answer

user166390 picture user166390 · Jun 29, 2011

Because this is just how Python works - keywords such as class and def are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be .. empty :-)

Anyway, the idiomatic approach is:

# stuff to run always here such as class/def
def main():
    pass

if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

See What is if __name__ == "__main__" for?

It does require source control over the module being imported, however.

Happy coding.