When I first came across the code if __name__ == “__main_” in a python script I was reading, I was utterly confused!
I had thought that python didnt have any kind of a main function, hence the confusion. But after hacking around a bit, when I found the need for this statement, it felt like a genius implementation.
I will try and explain in this blog post, the need to include the statement if __name__ == “__main__”: is some modules.
The main keyword included in Python is not like the main method implemented in other programming languages like C and C++. The execution of a python script implicitly starts from the top of the script, and the interpreter reads the script line by line in a top-down fashion.
While reading a Python file, the interpreter also defines some special variables. It sets the variable __name__ to equal to __main__ while the file (or module) is being executed independently, and sets it to the name of the module, if the module has been imported in some other script and that script is being executed.
To furnish an example which will dispell all doubts, try running the follwing code in your machine:-
I built two separate python scripts, by the name of one.py and two.py.
Now, when i run python one.py, i get the following output:-
Here one.py was executed independently, hence the variable __name__ had been set to __main__ and the if part of the if-else statemet was executed.
Now, when i execute python two.py, I see the following output :-
Now, just as the line ‘import one’ was read, the file one.py was executed by the interpreter. And now the variable __name wasn’t set to __main__, but instead set to the name of the module, which is equal to ‘one’. So the if part in one.py wasn’t executed, and instead the else part told us that the module had been imported in some other script.
Then two.py was executed further and we see the output as we should be seeing. Since two.py is being executed independently, we see that its __name__ variable is indeed equal to __main__.
So what is the use of including this statement in your module? By now you must have guessed it. This is exteremely helpful in case your module contains functions, along with some other code that may be directly executed. You can put that code inside this if __name__ == “__main__”: statement, and it will only be executed when this file is run independently. When you are importing that code into some other script, the various class and function definitions will be imported, but the main code won’t be executed.
I encourage you to hack around with these two files more, and also try and print one.__name__ in two.py to see if it actually prints out ‘main’ or ‘one’, i.e. the name of the module.