Home »
Python
What does if __name__ == '__main__': do in Python?
__main__ in Python: Here, we are going to learn what does if __name__ == '__main__': do in Python programming language?
By Sapna Deraje Radhakrishna Last updated : December 16, 2023
Understanding __name__ variable
In order to understand the details of __name__ variable and the if condition, let us go through a simple exercise. Run a simple python file with just the following lines and run the file as python3 code,
print("module_name :{}".format(__name__))
-bash-4.2$ python3 if_main.py
module_name :__main__
-bash-4.2$
In the above example, the output of the program states that the variable __name__ has a value of __main__. So, what happens is, in the background when python runs a file it goes through before it even runs any code, it sets a few special variables and 'name' is one of those special variables and when python runs the code it sets the '__name__' variable to '__main__'.
We can also import the modules, and when the modules are imported the variable __name__ is set to name the file.
Example
Create a file called second_module.py, and in second_module.py add the following lines and run the file.
import if_main
print("second module_name :{}".format(__name__))
-bash-4.2$ python3 second_module.py
module_name :if_main
second module_name :__main__
-bash-4.2$
In above example, we see that the imported file prints the file name and the second_module prints __main__, the reason being, the imported file is not run directly by python instead it is an imported file and hence the variable __name__ is set to the file name and the second_module is directly run by python and hence the variable __name__ is set to the __main__. Now returning to the subject of what does if __name__ == '__main__' do?
What does if __name__ == "__main__": do?
When the above condition is checked, it is to assert if the file is directly run by python or is it being imported. The following example explains the usage of the if condition,
File 1 : if_main.py
def main():
print("module_name :{}".format(__name__))
if __name__ == "__main__":
main()
else:
print("run from import")
File 2 : second_module.py
import if_main
print("second module_name :{}".format(__name__))
Example
-bash-4.2$ python3 second_module.py
run from import
second module_name :__main__
-bash-4.2$
-bash-4.2$ python3 if_main.py
module_name :__main__
-bash-4.2$
Advantages of using if __name__ == "__main__":
- The reason to use this is ensuring to run some code only when it is directly run from the main file and some code will be executed only when it is imported.
- The python file can be used either as a standalone program or a reusable module.
Python Tutorial