Programming can be more efficient and fast when users use a proper format and learn the use of every entity. Since Python supports extensive libraries and third-party modules, it is versatile, flexible, and interactive, so it is one of the most widely used languages with several applications.
But there are few specific variables or global variables that the Python interpreter defines before it executes the program. In this Python article, you will understand what if __name__ == '__main__' is and when to use it.
What is __main__ and if __name__ == '__main__' statement?
The __main__ indicates the name of an environment specified as "top-level scope" that executes all the top-level code. In Python, the "Top-level code" is the first user-specified module that triggers the execution of the program. The term "top-level" indicates it imports other Python modules the program requires for execution.
The module is a Python object that stores runnable code having variables, statements, functions, classes, definitions, etc. Programmers can use the condition if __name__ == '__main__' when they execute the code inside the if statement. The Python interpreter will not execute the code inside this if statement when users import the file's code as a module.
If users want to run the module that is the main program, they can set the __name__ variable as the __main__. The Python __name__ is a special variable that specifies the name of the class or the present module or the script which will invoke it. Let us use the statement to see how it works:
Open the Python IDLE or Python shell and see what the value of __main__ is:
Type the following command in an interactive mode:
>>> __name__
Output:
The value of the __name__ is __main__.
Again, type the following command to import the Python module to test whether the Python interpreter assigns the value to the module's __name__ variable:
>>> import random
>>> random.__name__
Output:
Here, in the output, users can see that the value for __name__ is 'random,' which specifies its name.
Using the Python __name__ variable values
Here, we will see the value of the special variable by placing it in the file __name__main.py.
Code Snippet:
print(" The value of __name__ is {}".format(__name__))
Output:
Explanation:
This single-line print command will generate an output showing the value of the __name__ using the string formatting method.
Examples of the if __name__ == '__main__'
Let us see and understand the different examples of the if __name__ == '__main__' to explore how imports and scripts function.
Example 1:
print("Here, we import the math module")
import math
print("The function_x before execution")
def function_x():
print("Function X")
print("The function function_y before execution")
def function_y():
print("Function Y {}".format(math.sqrt(20)))
print("We did not use the __name__ guard")
if __name__ == '__main__':
function_x()
function_y()
print("We have used the __name__ guard")
Output:
Explanation:
We ran our module or the source file as the main program in the above code snippet. The Python interpreter will assign the hard-coded string "__main__" to the __name__ variable in the conditional if statement.
Example 2:
Here, we will use the condition if__name__== "__main__" and see how it works:
Code Snippet:
def func1():
print("This is out first function executed")
def func2():
print("This is out second function executed")
def func3():
print("This is out third function executed")
if __name__ == "__main__":
func1()
func2()
func3()
Output:
Explanation:
We used three different functions and executed each of them one by one to check if the if __name__ is equal to __main__. The Python interpreter only runs the Python file's code inside the if statement when it is directly called instead of calling it while importing as the module.
Since every developer to well-known in the concept of main, so specifying the function main() is a standard naming convention that will improve the program's readability.
if__name__== "__main__" in Action:
Users use the if-statement to execute blocks of code only if they work with the main executable program. It allows their program to be self-executable but accessible to other Python modules using users who want to import some functionality without running the code directly.
Code Snippet:
def add(x, y):
return x+y
if __name__ == "__main__":
print(add(7, 3))
Output:
Explanation:
In this example, we used the script directly, assigned the __name__ keyword to __main__, and the Python interpreter executed the code block under the if __name__ == "__main__" condition. We saved the program as main.py, which contains a function called add() and gets called only from the main context.
What are the applications of __name__ == "__main__" in development?
In this section, we are defining the applications of __name__ == "__main__" when creating a Python script:
One of the most helpful phases in programming is testing which is a good practice and allows users to check or test bugs, ensuring their code runs as it should. In such cases, users use these test files to import a function or object into them. In these circumstances, users typically will not want the Python script will execute as the main module.
Suppose in a case where users want to create a library but would like to add a demo or any special run-time instance; they will use this statement for this particular purpose. Using the if-statement will leave the Python modules that operate the code as a library unchanged.
Conclusion:
Using the __name__ == "__main__" provides efficient methods to create a structured program with large modules. It will execute code blocks only when users directly run their Python script. Using this in a Python program can benefit in several ways and allows the code to maintain distinct characteristics when users execute it as a program rather than a module.