What does if __name__ == "__main__" mean in Python ? Quickly Explained
Understanding Python Idioms
Let’s try to understand the left hand side of this idiom:
if __name__
What exactly __name__ is ?
__name__ is a special variable in python whose value depends on how the code which contains is getting executed.
When we run the .py file as a standalone program, a script,
__name__ variable equals “__main__”.
If the file containing this code is being imported, __name__ variable is set to module’s name.
So, clearly, if you execute a testFile.py file directly like this: python testFile.py
print("__name__ is set to %s "% __name__)
def testFunc():
print("I am Test Func")
if __name__ == "__main__":
testFunc()
Output:
__name__ is set to __main__
I am Test FuncAnd if you import the testFile in otherTestFile.py:
import testFileOutput:
__name__ is set to testFileAlso, testFunc does not gets called as it fails the if condition.
Thanks !

