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

You can often see this (option a):

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

And now I wonder why not this (option b):

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

Or at least this (option c):

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

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

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

+6
source share
2 answers

Why limit the main() function to just the command line?

Having defined the main() function in the module area, you can now wrap your script and change the way it is called. Maybe you want to set the default arguments to sys.argv, maybe you want to reuse the code in another script.

+11
source

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

+4
source

Source: https://habr.com/ru/post/921931/


All Articles