The world’s leading publication for data science, AI, and ML professionals.

Entry Point of A Python Application

Introduction of __name__ and __main__ using examples

Photo by Prettysleepy on Pixabay
Photo by Prettysleepy on Pixabay

I believe you must have ever seen if __name__ == '__main__' in some Python source code repo, application or libraries. You may or may not know what it is, because you definitely don’t need it if you’re a typical data scientist who uses Jupyter Notebook most of the time. Or, you may simply imitate to use this expression even though it is not quite sure what it does, just like me when I started to learn Python 🙂

In this article, I’ll introduce you what does it do, how does it work and when to use it. As stated in the title, it can be generally referred to as an "entry point" of application.

A Basic Example – What does it do?

Photo by MasterTux on Pixabay
Photo by MasterTux on Pixabay

Let me use a simple example to demonstrate what does it do.

Suppose we are developing an extremely simple Python application that can calculate the area of shapes. Let’s start from a circle.

To calculate the area of a circle, we need a value of pi. Of course, the best way to get the PI value is to use the built-in package math.pi. However, let’s suppose we have to define it by ourselves.

pi = 3.1415926
def main():
    print('pi is', pi)
main()

As shown in the screenshot, I have created a module called if_name_test, and I have also created a Python file called mylib.py which will be used to store all the constants.

The pi value is defined here, and I also want to create a main() method that is used to test all the constants and methods. At the end of the script, the main() method is called to display the pi value.

Now, let’s run the script file.

No problem. The pi value is printed because we have run the main method.


Now, let’s create another Python file called calculate.py that is used to calculate the areas of shapes. It will import the constant value pi from mylib. Please be noted that the directory if_name_test is created in the working directory so that we need to import from if_name_test.mylib rather than .mylib.

from if_name_test.mylib import pi
def get_circle_area(r):
    return r * (pi ** 2)
def main():
    r = int(input('Please input the radius of the circle: '))
    print(f'The area of the circle with radius {r} is: {get_circle_area(r)}')
main()

In here, we define the function calculating the area of a circle. Then, another main() method is defined here to ask the user to input the radius and return the area based on the input.

Let’s see what happy if we run the script file.

Everything is fine, except the pi value was printed. We never ask it to be printed, how it just did that? It is because we have imported mylib, and the main() method is called at the end of the file mylib.py.


Here is where we need to use the built-in variable __name__. Let’s add the if condition to the main() method in mylib.py.

if __name__ == '__main__':
    main()

If you’re using PyCharm like me, you may notice that there is a green play button on the if condition we’ve just added. PyCharm recognises the "entry point" so that it add this shortcut to run the script for us. If we run the file, the pi value is still output as usual.

However, if we come back to the calculation.py file and run it, the pi value will not be printed anymore.

We don’t have to modify calculation.py, just by adding an if condition to our lib file and do the trick.

How does it work?

Photo by pixel2013 on Pixabay
Photo by pixel2013 on Pixabay

I will not copy-paste the wordage from the official documentation like most of the tutorials do because you can always do that by yourselves. Instead, I will demonstrate this using examples.

In fact, the if condition works must because

  • When we run the file mylib.py, the __name__ is exactly '__main__'
  • When we import the file mylib.py from calculation.py, it must not be '__main__' so that the main() method will not be called.

Let’s verify this by printing the __name__ variables in both of the files.

In mylib.py, we add

print(f'In mylib.py, the __name__ variable is {__name__}')

In calculation.py, we add

print(f'In calculation.py, the __name__ variable is {__name__}')

Tips: you may also use the __file__ variable to get the file name rather than manually input them 🙂

Now, let’s run the calculation.py file.

OK. The variable __name__ will be assigned by the value __main__ from the file we run. In this case, the file mylib.py isn’t the starting point but imported as a module, it is assigned with the module name. Therefore, the main() method in mylib.py will not be called.


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 __name__ variable '__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 main().

These are totally irrelevant!

Let’s change the method name in mylib.py from main() to my_constants(). Of course, inside the if condition we need to call the method that had been renamed.

pi = 3.1415926
def my_constants():
    print('pi is', pi)
if __name__ == '__main__':
    my_constants()

And let’s run the file again.

No problem at all. So, don’t be confused by so many main 🙂

When to use it?

Photo by Tama66 on Pixabay
Photo by Tama66 on Pixabay

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.

Basically, the 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.

Summary

Photo by Tama66 on Pixabay
Photo by Tama66 on Pixabay

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 testing whether it equals to '__main__'.

Also, I have demonstrated how the __name__ variable works and some points that are 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.

Join Medium with my referral link – Christopher Tao

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)


Related Articles