Is there a shorter form of this?
if __name__ == '__main__':
It is pretty tedious to write, and also doesn't look very nice in my opinion :)
Is there a shorter form of this?
if __name__ == '__main__':
It is pretty tedious to write, and also doesn't look very nice in my opinion :)
PEP299 proposed a solution to this wart, namely having a special function name __main__
. It was rejected, partly because:
Guido pronounced that he doesn't like the idea anyway as it's "not worth the change (in docs, user habits, etc.) and there's nothing particularly broken."
http://www.python.org/dev/peps/pep-0299/
So the ugliness will stay, at least as long as Guido's the BDFL.
Basically every python programmer does that. So simply live with it. ;)
Besides that you could omit it completely if your script is always meant to be run as an application and not imported as a module - but you are encouraged to use it anyway, even if it's not really necessary.
After asking this question, I decided to make a solution to it:
from automain import * # will only import the automain decorator
@automain
def mymain():
print 'this is our main function'
The blog post explains it, and the code is on github and can be easy_installed:
easy_install automain
It's definitely a wart in the language, as is anything that becomes boilerplate and gets copied and pasted from file to file. There's no shorthand for it.
As warts and boilerplate go, though, at least it's minor.
It is pretty tedious to write, and also doesn't look very nice in my opinion :)
My perfectionism also finds Python main
s a tad ugly. So, I searched for solutions and finally used the following code.
Copy / pasted code :
# main_utils.py
import inspect
from types import FrameType
from typing import cast
def is_caller_main() -> bool:
# See https://stackoverflow.com/a/57712700/
caller_frame = cast(FrameType, cast(FrameType, inspect.currentframe()).f_back)
caller_script_name = caller_frame.f_locals['__name__']
return caller_script_name == '__main__'
#!/usr/bin/env python3
# test.py
# Use case
import main_utils
if main_utils.is_caller_main():
print('MAIN')
else:
print('NOT MAIN')
Source on GitHub Gist :
<script src="https://gist.github.com/benoit-dubreuil/fd3769be002280f3a22315d58d9976a4.js"></script>