Find out what is if __name__ == “__main__” in Python and its purpose. Learn about the __name__ attribute and when its value is set to “__main__”.
if __name__ == "__main__"?
You might have seen the following line of code in numerous python programs.
if __name__ == "__main__"
But what is its purpose? Let’s find out.
It is simply an if statement having the condition
__name__ == "__main__"
The condition is to check if the attribute
__name__ has the string type value
__name__ Attribute and
Every module in python has some special attributes and
__name__ is one of them. The value of this module is usually set to
"__main__" or to contain the name of the current module.
Let’s understand this concept with the help of examples.
I’ve created a file named some_module.py and written the following code into it.
print("This is a demo function of some_module.")
if __name__ == "__main__":
print("The program is executed as the main program.")
print("As you can see, the value of __name__ is", __name__)
print("That's why the control is inside the if statement body.")
print("Calling demo() Function")
Now, to execute the python code written in the file,
some_module.py, I used the following command.
And it printed the following output to the console.
The program is executed as the main program. As you can see, the value of __name__ is __main__ That's why the control is inside the if statement body. Calling demo() Function This is a demo function of some_module.
This code was simple. As the value of the attribute
__name__ matches with the value
__main__, therefore, every single statement that was written inside the if block is executed and hence the function
demo() is also being called.
Now we’ve created a new file named
try.py and inside this file, the following python code is written.
#Calling demo() function from some_module
Now, clearly observe the output of the above code by running the
try.py file using the following command.
As you can see in the output,
__name__ still has the value
__main__ but we refer the
__name__ attribute for
some_module it gives the value
This is a demo function of some_module. __main__ some_module
I hope now you have clear idea about the value of the
If it’s called within the module itself, it has the value
__main__ while if it is called in some other module by the original module reference, its value is the name of the module itself.
Also, the if block code is now not executed as the value of the attribute
__name__ is not anymore
I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!