Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must Python script define a function as main?

Must/should a Python script have a main() function? For example is it ok to replace

if __name__ == '__main__':
  main()

with

if __name__ == '__main__':
  entryPoint()

(or some other meaningful name)

like image 471
Celeritas Avatar asked Jul 20 '15 17:07

Celeritas


People also ask

Do you need to define a main function in Python?

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.

Is Main class mandatory in Python?

The main function is mandatory in programs like C, Java, etc, but it is not necessary for python to use the main function, however it is a good practice to use it. If your program has if __name__ == “__main__” statement then the program is executed as a standalone program.


1 Answers

Using a function named main() is just a convention. You can give it any name you want to.

Testing for the module name is just a nice trick to prevent code running when your code is not being executed as the __main__ module (i.e. not when imported as the script Python started with, but imported as a module). You can run any code you like under that if test.

Using a function in that case helps keep the global namespace of your module uncluttered by shunting names into a local namespace instead. Naming that function main() is commonplace, but not a requirement.

like image 153
Martijn Pieters Avatar answered Oct 01 '22 17:10

Martijn Pieters