fir3net
PPS-Firenetbanner-780.5x190-30-03-17

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

Tags: Python

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001