When i started with python, i came upon this line of code a lot. Mainly in 2 contexts:
1. At the start of a file,
2. At the end of the file to run a function which contains most of the code and to run additional tasks.
Now the confusion usually is that everything works fine even without checking __name__==”__main__”
Every module (simply a file consisting of python code) in python has a name and statements in the module can can find out that name.
When the python Interpreter reads the source file it executes all the code found in it. But before executing the code, it defines a few special variables. If the python interpreter is running a module (our source file) as the main program, it sets the special __name__ variable to have the value __main__. If the file is being imported from another module, __name__ is set to the module’s name
Q: What if we want to run the code block only if the program was used by itself and not when it was imported from another module? This is achieved using __name__ attribute of the module.
1. Executing e2.py (image 2)
$ python e2.py
square of 2 is: 4
this program is run by itself
2. Importing e2.py
$ import e2.py
this program is being imported by another module
What it means:
1. In example 1, the source file is run directly. Hence, __name__ attribute is set to __main__ and the if condition is set to True.
2. In example 2, the source file is imported. Hence, __name__ attribute is set to “e2”. Else condition is executed thus.
Hope it helps!