pythonmodulepython-import

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


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?


Solution

  • 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.

    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()