Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a main() method in a simple Python script?

Tags:

python

I have a lot of simple scripts that calculate some stuff or so. They consist of just a single module.

Should I write main methods for them and call them with the if __name__ construct, or just dump it all right in there?

What are the advantages of either method?

like image 1000
Martin Ueding Avatar asked Apr 04 '11 21:04

Martin Ueding


People also ask

Does Python script need main method?

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.

Should main be at the top Python?

The usual convention is to put them at the end of the script. And of course you can't call main before you define it.

What is the purpose of a main function Python?

In Python, the role of the main function is to act as the starting point of execution for any software program. The execution of the program starts only when the main function is defined in Python because the program executes only when it runs directly, and if it is imported as a module, then it will not run.


1 Answers

I always write a main() function (appropriately named), and put nothing but command-line parsing and a call to main() in the if __name__ == '__main__' block. That's because no matter how silly, trivial, or single-purpose I originally expect that script to be, I always end up wanting to call it from another module at some later date.

Either I take the time to make it an importable module today, or spend extra time to refactor it months later when I want to reuse it for something else.

Always.

Every time.

I've stopped fighting it and started writing my code with that expectation from the start.

like image 87
Kirk Strauser Avatar answered Sep 28 '22 03:09

Kirk Strauser