What does if __name__ == "__main__" do?
It's good practice to apply this in your scripts. Find out why and how this works.
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:
- We run it as the main program with
- We import the file in another file with
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.
When the Python interpreter reads a source file, it does two things:
- First, it sets a few special variables like
- Then it executes all of the code it finds in the file
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
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
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.
StackOverflow answer to the question
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
PySaaS: The Pure Python SaaS Starter Kit
🚀 Build a software business faster with pure Python: Link*