{"id":767,"date":"2013-05-01T00:00:00","date_gmt":"2013-05-01T00:00:00","guid":{"rendered":"https:\/\/fir3netwp.gmsrrpobkbd.com\/2013\/05\/01\/python-what-does-qif-name-qmainqq-mean\/"},"modified":"2021-07-24T18:03:57","modified_gmt":"2021-07-24T18:03:57","slug":"python-what-does-qif-name-qmainqq-mean","status":"publish","type":"post","link":"https:\/\/www.fir3net.com\/Programming\/Python\/python-what-does-qif-name-qmainqq-mean.html","title":{"rendered":"Python – What does ‘if __name__ == “__main__”‘ mean ?"},"content":{"rendered":"
Within a Python program you may see the following syntax,<\/p>\n
if __name__ == \"__main__\":
...(your code)...<\/pre>\nWhat does this mean ?<\/strong><\/h4>\n
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.<\/p>\n
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.<\/p>\n
Heres a very quick example that shows you the difference in namespaces between a directly executed Python command and a module.<\/p>\n
>>> print __name__
__main__
>>> import datetime
>>> print datetime.__name__
datetime<\/pre>\n","protected":false},"excerpt":{"rendered":"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 … Read more<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[36],"tags":[],"yoast_head":"\n
Python - What does 'if __name__ == "__main__"' mean ? - Fir3net<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n