What does if __name__ == "__main__" do?

Patrick Loeber

It is boilerplate code that protects users from accidentally invoking a script when they didn’t intend to, and it’s good practice apply it. This makes a difference for these two use cases:

In the latter case usually we only want to import the module and then later in the code execute some functions or use a class from this file. This is where the if __name__ == "__main__" statement comes into play and works as a guard.

Let’s find out why and how this works.

Special variable

When the Python interpreter reads a source file, it does two things:

Let’s have a look at the following example where we correctly use the if __name__ == "__main__" statement:

# This is foo.py def functionA(): print("Function A") if __name__ == "__main__": print("Running foo") functionA()

Case 1: Run it as the main program with python foo.py.

The Python interpreter will assign the hard-coded string "__main__" to the __name__ variable, thus the code in the if statement is executed:

$ python foo.py Running foo Function A

Case 2: Import foo in another module.

The interpreter will assign "foo" to the __name__ variable in the foo module. Thus, the code in the if statement is not executed, and functionA will not run.

# This is bar.py import foo if __name__ == "__main__": print("Running bar")
$ python bar.py Running bar

Without the if __name__ == "__main__" in foo.py, the output would be the following:

$ python bar.py Running foo Function A Running bar

Usually this is not what we want. So if you want to run code in a file, it’s good practice to wrap all of this code into a if __name__ == "__main__" statement.

More Resources:

StackOverflow answer to the question

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses