7

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)

Celeritas
  • 14,489
  • 36
  • 113
  • 194
  • 1
    Yes. That bit of magic just stops your main function from being run when your script is imported. This just says "If I'm the main script, call this function". – Morgan Thrapp Jul 20 '15 at 17:48
  • @MorganThrapp: Are you answering the question in the title or the body? Because they are contradictory. ;) – Ethan Furman Jul 20 '15 at 22:16
  • Oops, didn't even notice that. I was answering the question about if it's okay to rename `main()` – Morgan Thrapp Jul 20 '15 at 23:27

2 Answers2

10

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Actually it's a trick to _make_ the code run (not prevent it) when the script is executed as the `__main__` module. – martineau Jul 20 '15 at 18:10
  • 2
    @martineau: no, all code at the global level runs when a module is imported (be it run directly as a script or because it was imported indirectly). The `if __name__` test then *disables* the code when you are not running it directly as a script. I see that my text got the two muddled up, fixed that. – Martijn Pieters Jul 20 '15 at 20:32
7

No, a Python script doesn't have to have a main() function. It is just following conventions because the function that you put under the if __name__ == '__main__': statement is the function that really does all of the work for your script, so it is the main function. If there really is function name that would make the program easier to read and clearer, then you can instead use that function name.

In fact, you don't even need the if __name__ == '__main__': part, but it is a good practice, not just a convention. It will just prevent the main() function or whatever else you would like to call it from running when you import the file as a module. If you won't be importing the script, you probably don't need it, but it is still a good practice. For more on that and why it does what it does, see What does if __name__ == "__main__": do?

Community
  • 1
  • 1
michaelpri
  • 3,521
  • 4
  • 30
  • 46