Python is a powerful programming language that offers tons of features and versatility. If you are a Python developer, then you may have frequently come across ‘__name__ == __main__’ (also called name-main idiom) while reading other people’s code and wondered what it does. In this article, we will learn what this name-main idiom means, how this expression works and how to use it correctly.
Before we understand what __name__=__main__ does, we need to separately learn how __name__ variable works and the difference between script and module in Python.
Script vs Module
A Python module is a self-contained file of variable definitions, classes, functions and commands that is meant for reuse. It is meant to be imported by other Python scripts and not to be executed on its own.
A Python script is a file with a sequence of definitions, functions and commands. It is a standalone program meant to be executed on its own. It can, however, import other modules into it, for increased functionality.
How does __name__ variable work
__name__ is a special variable managed by Python during runtime. When a Python developer runs a script, the interpreter will automatically set __name__ variable to one of the following 2 values:
- It is set to __main__ if the script is run as a standalone program
- It is set to the name of the module, if the script is imported into other scripts
Here is an example to demonstrate it. Let us say you create a Python file test.py with the following code which displays the value of __name__ variable.
print("__name__ in test.py: " + __name__)
Let us say you have another file app.py which imports the above file, using import statement, and also prints __name__ variable’s value.
import test
print("__name__ in app.py: " + __name__)
When you run app.py file, it will print the value of __name__ variable twice, once from inside test.py and once from inside app.py.
$ py app.py
__name__ in test.py: test
__name__ in app.py: __main__
What does if __name__ == “__main__”: do?
The name-main idiom works like any other if conditional expression in Python. If the value of __name__ variable is __main__ then all code nested under it will be executed. Else it will be skipped. As mentioned earlier, __name__ is a Python variable controlled by the interpreter. Its value is __main__ when you run the python script as a standalone script. Its value is equal to the name of the module if it is imported in other scripts.
Here is a simple example test.py to demonstrate it.
# test.py
def main():
print('Hello World')
if __name__ == '__main__':
main()
In the above code, we have defined main() function. But it is called only if name-main condition is true. In other words, it is called only if your script is executed as a standalone script, and not when it is imported elsewhere.
$ python test.py
'Hello World'
On the other hand, if you import this code in other script, say test2.py, it will not call main() function.
# test2.py
import test.py
print('Bye Bye')
Let’s try running this code.
$ python test2.py
Bye Bye
On the other hand, if you modify test.py to include some code outside the name==main condition, it will be executed. Here we have added a print statement outside the name-main condition.
# test.py
def main():
print('Hello World')
print('Good Morning')
if __name__ == '__main__':
main()
Now let us try running test2.py once again.
$ python test2.py
Good Morning
Bye Bye
Name-main condition allows you to separate reusable parts of your code from the executable ones. Therefore, it also allows you to protect your code from being knowingly or unknowingly used by other scripts.
Please note, you can always have multiple name-main blocks in your code.
# test.py
def main():
print('Hello World')
if __name__ == '__main__':
print('Good evening')
print('Good Morning')
if __name__ == '__main__':
main()
When you run the script test2.py which imports the above test.py, you will get the following output.
$ python test2.py
Good Morning
Bye Bye
As you can see above, both the name-main blocks in test.py were skipped during execution.
Benefits of using name==main
There are several benefits of using name==main condition:
- It allows you to modularize code by clearly separating the executable and reusable parts of your code. The reusable parts of your code can be easily imported into other scripts. On the other hand, the executable code will be executed as standalone script.
- Name-Main idiom allows you to easily test specific parts of your code when it is executed on its own, without affecting other parts of the code.
- It also prevents unexpected code execution by skipping the part nested within __name__==__main__ condition, in case your code is imported in other scripts.
- It improves code readability by clearly separating executable and reusable code in your file.
When to use name equals main
There are several use cases when it is advisable to use name-main condition:
- One of the most common ways to use this name-main idiom is when you want your script to work as a standalone program as well as importable module.
- Another use case is when you want to prevent certain code from being executed when it is imported by other scripts. In this case, you can put that code in name-main idiom. For example, you may need to fetch user input from your file when you run it as a script but not when it is imported by other scripts.
- You can also use name-main idiom for unit testing by running your file from a separate module without running the code under name-main idiom. This will prevent unexpected errors.
- Alternatively, you can also include test code inside name-main condition and run it as a standalone script so that it does not run when the script is imported elsewhere.
- You can use it to demonstrate certain capabilities of the script which will not be executed when it is imported.
When not to use name equals main
On the flip side, there are a couple of use cases when it is not advisable to use name-main idiom:
- If your script is too large or complex, then it is better to create separate file for the module part and script part, instead of cramming everything into a single file
- If your Python script is meant to be run purely as a script and not as a module, then you do not need to include name-main condition.
Conclusion
In this article, we have learnt what __name__==__main__ does, how it works, when to use, when not to use it. To summarize, the code included under name-main condition will be executed only when your Python file is run as a standalone script and not imported as a module. The rest of the code will be executed whether you run it as a standalone script or import it as a module in other files.
Also read:
How to Check If Element is Hidden in jQuery
What Are Metaclasses in Python
What Does Yield Keyword Do in Python
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.