What is __name__ == "__main__" in Python?
Python snippets use __name__ == "__main__" checks to ensure that the module-specific code is ran only when they are run directly via Python. Let's see that with an example
If you are a Python beginner, you often see
if __name__ == '__main__'and get confused about what it does. You are not alone. Most of my students at #PythonToProject Bootcamp struggle with this as well.
if __name__ == '__main__':ensures that the snippet under it gets executed only when the file is run directly.
print ("app.py __name__=", __name__)
if __name__ == '__main__':
print ("inside main check block")
When you run this code
python app.pyyou will get the following output
inside main check block
Whereas if you import
appinto another module
print ("temp.py __name__=", __name__)
The output will be