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)

3
  • 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". Commented Jul 20, 2015 at 17:48
  • @MorganThrapp: Are you answering the question in the title or the body? Because they are contradictory. ;) Commented Jul 20, 2015 at 22:16
  • Oops, didn't even notice that. I was answering the question about if it's okay to rename main() Commented Jul 20, 2015 at 23:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually it's a trick to make the code run (not prevent it) when the script is executed as the __main__ module.
@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.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.