I understand the purpose of it, however I was wondering what is the most pythonic way to use if __name__ == '__main__'
?
I'm divided between putting all my code in a main()
function and calling it like:
if __name__ == '__main__':
main()
Or not bothering with that and just writing all top-level code there:
if __name__ == '__main__':
# all top-level code...
If you write all the code under the __name__
guard, you can never re-use that code. If on the other hand you put the code in a main()
function, you can always import that function elsewhere and call it.
You'd use this for console scripts registered in your setup.py
when packaging your project with setuptools, for example. That way you can test your script without installing it first, and run it as a installed script (which will add dependencies to sys.path
before calling your main()
function).
I don't know if one is more idiomatic than the other, but one reason to put everything in a main
function and call it is that local variable lookups are faster than global variable lookups (see this question for an explanation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With