Why is the main() function not defined inside the

2019-06-20 07:55发布

问题:

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() ).



标签: python main