Reputation: 637
By convention, Python scripts that are run directly and not imported have the line if __name__ == '__main__':
. This is to prevent code that should not be executed from running. It can also be used the other way around to only allow code to be run if it is not executed directly, if __name__ != '__main__':
Are there any benefits/downsides to calling an arbitrarily named "main" function inside the conventional if statement mentioned above? For example:
def main() -> None:
print('Done')
return
if __name__ == '__main__':
main()
Benefits:
return
import sys
and use sys.exit(0)
Downsides:
What other benefits and/or downsides are there? Does it make the interpreter do more work if the code is in a function as opposed to not in a function?
Upvotes: 3
Views: 830
Reputation: 2977
It is all about code/module management, without the main
sentinel, the code would be executed even if the script were imported as a module.
Upvotes: 2