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

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


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.

~ Answered on 2011-06-29 16:15:59


Most Viewed Questions: