You may have seen a curious syntax in some Python programs that includes a string like if __name__ == “__main__”: main(). Some might refer to it as the def main if name main idiom. The if __name__ == “__main__” has some benefits that you may want to consider, especially if you are a fan of single-file Python scripts. In this tutorial about if __name__ == “__main__”, we’ll take a look at what this pattern offers, and why it is smart to use it.
Not Every Python File Is A Script
Individual Python files can be used as part of a library or module to provide services to other parts of a larger program. These types of files are not meant to run individually or in isolation. For example, this code defines a function that you would import into another file and run there.
def library_function():
# do cool stuff
return 'cool stuff'
That means this code would not benefit from the if __name__ == “__main__”: main() pattern.
Programming Language Boilerplate
Most languages have some boilerplate code set up before you can even write any useful code to make something happen. Java programmers are all too familiar with this needed boilerplate code.
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
In C++ you often see this boilerplate code to define the main function.
#include <iostream>
int main() {
std::cout << "Hello, C++!";
return 0;
}
Python is flexible enough to let you omit any boilerplate if you so choose. This code in a single Python file runs great when you simply run that file. This is known as a script.
print('It works!')
This makes Python very accessible to beginners since it is so flexible. You can get something working in just a few seconds.
Python __name__ Variable
To understand how if __name__ == “__main__”: main() works, we need to first understand what the __name__ variable is in Python. If we print it out in a Python file it shows the following:
other_lib.py
print(f'__name__ = {__name__}')
__name__ = __main__
When Python runs a file before it even runs any code it sets a few special variables. The __name__ variable is one of those special variables. When Python runs a Python file directly, as a script, it sets the __name__ variable to __main__. In a single Python file that runs as a script, the __name__ variable has a value of __main__. This is what happened just above when we ran the other_lib.py file as a script. If the file is imported, however, the value of __name__ will have something else. It will follow the convention of package.path.to.module. Here we have a second file, and we are simply importing the other_lib module into the file and running the file. Another way to look at this is that when Python imports a file, __name__ is set to the name of the imported file. It’s also important to understand that whenever you import a file, Python runs any code that is contained in that imported file.
testing.py
import other_lib
__name__ = other_lib
Is The File A Script?
Herein lies the big benefit of using the if __name__ == “__main__”: main() pattern. It allows you to check whether the current file is being run as a script, or as an imported library. If you see that the __name__ variable has a value of __main__ then you know that it is running as a script. If the __name__ variable has any other value, then we know it is being imported.
Why Do This Check?
Checking to see if the code is being run as a script or imported benefits the user of the code. If a person reading your code sees the if __name__ == “__main__”: main() pattern, it is a signal to that person that this file is a script and that they can run it directly. If a person is reading a Python file and does not see the if __name__ == “__main__”: main() pattern anywhere, then it should be an indicator that you can not, or at least should not try to directly run that file. This should tip you off that this file is part of a library that should only be used when it is imported.
This is not enforced by the Python language itself, but it is a good convention to follow if you would like to let users of your code know if your code is a script that can be run, or a library to be imported. This way there is no guessing where the entry point for the program is, the if __name__ == “__main__”: main() pattern makes it explicit.
The popular Pycharm IDE is able to recognize this pattern right away. Notice that there is a green arrow on line 5 showing you that this is the entry point into the program and that it can be run.
Since the other_lib.py file has no mention of if __name__ == “__main__”: main(), Pycharm is smart enough to know that this file is likely not intended to be run directly, but to be used an import.
The default main.py script in PyCharm
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files,
# tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
Extracting main() function
Part of this pattern involves extracting the main() function to its own function definition. You might be wondering, why can’t I just write my code inside of the if block? You could, but you may inadvertently be introducing variables into the global scope which is something you want to avoid at all costs.
Python if __name__ == “__main__”: main() Summary
This is a pattern of code that protects users from accidentally running a script when they didn’t intend to. This pattern is also known as a guarded script.
When importing a guardless script into another script, the second script will run the first script using the second script’s command-line arguments which is usually not intended.
If you have a class you wrote in the guardless script and then save it to a pickle file, the unpickling in another script will trigger an import of the guardless script, once again creating the same unintended arguments.
To make you Python code safer, and easier to reason about, it makes sense to use the if __name__ == “__main__”: main() guarded script pattern.