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__

>>> import datetime
>>> print datetime.__name__

Tags: Python

About the Author


R Donato

Rick Donato is the Founder and Chief Editor of He currently works as an SDN/NFV Solutions Architect and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001