TheLearningDev's Blog


TheLearningDev's Blog


What is __name__ == "__main__" in Python?

Bhavani Ravi's photo
Bhavani Ravi
ยทNov 22, 2022ยท

1 min read

Python snippets use name == "main" checks to ensure that the module-specific code is run only when they are run directly via Python.

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 Bootcampstruggle with this.

The if __name__ == '__main__': ensures that the snippet under it gets executed only when the file is run directly.

Running Python module


print (" __name__=", __name__)

if __name__ == '__main__':
    print ("inside main check block")

You will get the following output when you run this code python __name__=__main__
inside main check block

Importing Python module

Whereas if you import app into another module

import app

print (" __name__=", __name__)

The output will be __name__=app __name__=__main__
Share this