Why is the main() function not defined inside the if '__main__'?

时光毁灭记忆、已成空白 提交于 2019-12-23 09:35:12

问题


You can often see this (variation a):

def main():
   do_something()
   do_sth_else()

if __name__ == '__main__':
    main()

And I am now wondering why not this (variation b):

if __name__ == '__main__':
   do_something()
   do_sth_else()

Or at least this (variation c):

if __name__ == '__main__':
    def main():
        do_something()
        do_sth_else()

    main()

Of course the function calls inside main() might not be function calls, they just represent anything you might want to do in your main() function.

So why do people prefer variation a over the others? Is it just style/feeling or are there some real reasons? If possible, please also link sources.


回答1:


Why limit your main() function to command line usage only?

By defining a main() function at module scope, you can now wrap your script and alter how it is called. Perhaps you want to set default arguments in sys.argv, perhaps you want to reuse the code in another script.




回答2:


This is because there are two ways of using Python scripts. One from the command line and another when importing it from another script. When you run it from command line, you want to run main() function and when you import it you may not want to run main() function until you need it ( you just want to import main() ).



来源:https://stackoverflow.com/questions/11775494/why-is-the-main-function-not-defined-inside-the-if-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!