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.
In Short: It Allows You to Execute Code When the File Runs as a Script, but Not When It's Imported as a Module. For most practical purposes, you can think of the conditional block that you open with if __name__ == "__main__" as a way to store code that should only run when your file is executed as a script.
__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
if __name__ == "__main__" in Action We use the if-statement to run blocks of code only if our program is the main program executed. This allows our program to be executable by itself, but friendly to other Python modules who may want to import some functionality without having to run the code.
In Python, it is not necessary to define the main function every time you write a program. This is because the Python interpreter executes from the top of the file unless a specific function is defined.
Python files are called modules and they are identified by the . py file extension. A module can define functions, classes, and variables. So when the interpreter runs a module, the __name__ variable will be set as __main__ if the module that is being run is the main program.
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.
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With