+ 2

When it is used and why: if __name__ == "__main__":

23rd Jan 2018, 5:28 AM
Tincture
3 Answers
+ 10
I use that code idiom for unit tests, so that the test libraries are imported and the tests are run only when the code is run directly. If the file is imported as a module into other code, __name__ == "__main__" is false, and the tests are skipped.
23rd Jan 2018, 6:26 AM
Eric Blinkidu
Eric Blinkidu - avatar
+ 7
23rd Jan 2018, 5:44 AM
Travis
Travis - avatar
+ 7
__name__ returns the scope of the function. If the file is a executed, __name__="__main__" However, if it is imported as a module, it won't. In other words, commands under the 'if __name__=="__main__"' will be executed if it is run as the main acript but will not run if it is imported as a module.
23rd Jan 2018, 6:39 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar