Python – What does ‘if __name__ == “__main__”‘ mean ?

Within a Python program you may see the following syntax,

if __name__ == "__main__":
    ...(your code)...

What does this mean ?

When a Python program is run directly it runs within the __main__ namespace. However when a python script is imported as a module it runs within its own namespace.

This statement checks the namespace and in turn allows you to define which code should ONLY be executed when the Python program is run directly.

Heres a very quick example that shows you the difference in namespaces between a directly executed Python command and a module.

>>> print __name__
__main__

>>> import datetime
>>> print datetime.__name__
datetime
Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial