Reputation: 15063
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)
Upvotes: 7
Views: 1629
Reputation: 1123240
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.
Upvotes: 10
Reputation: 3651
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?
Upvotes: 7