Well, I could stop here since I have used the example to demonstrate how the
__name__ variable works. However, I would like to show one more example because I was actually confused by the method
main() and the value of the
'__main__' when I learned this.
It makes sense to use
main() as the method name because most of the other language might be compulsory to use the name as the entry point. However, a learner of Python might think the value of
__name__ variable is
'__main__' because we defined the method
These are totally irrelevant!
Let’s change the method name in
my_constants(). Of course, inside the if condition we need to call the method that had been renamed.
pi = 3.1415926def my_constants():
print('pi is', pi)if __name__ == '__main__':
And let’s run the file again.
No problem at all. So, don’t be confused by so many
As above-mentioned, you probably will never the
__name__ variable in Jupyter Notebooks if you’re a typical data scientist. However, it is recommended to be used in whatever the Python applications that
Any files having something you don’t want them run if the file is not the entry point.
A typical example will be Flask applications. If you’re using/learning Python to develop web services using flask, you must have seen that the
app.run() method is called inside the if-name condition.
app.run() method will be called when we run the Flask main file to test our API endpoints in the developing environment. However, Flask applications are generally not recommended to be directly run using Python in the production environment. Instead, we using Nginx + uWSGI to run start web services for many reasons such as monitoring purposes. In this case, the
app.run() in the Python script file will not be the entry point anymore. To prevent it from running in place, we must put it in the if-name condition.
In this article, I have introduced the usage of the
__name__ variable in an “if-name” condition to verify whether the current file is the entry point of the Python application by test whether it equals to
Also, I have demonstrated how the
__name__ variable works and some points that easy to be confused.
Finally, Flask is used as an example to show when to use the “if-name” condition. It is very important to understand how it works and when we must use it in order to develop a reliable Python application.
Life is short, use Python!