简体   繁体   中英

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)

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 (ie 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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM