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 :)
if __name__ == "__main__" in ActionWe use the if-statement to run blocks of code only if our program is the main program executed. This allows our program to be executable by itself, but friendly to other Python modules who may want to import some functionality without having to run the code.
If you import this script as a module in another script, the __name__ is set to the name of the script/module. Python files can act as either reusable modules, or as standalone programs. if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
__main__ is the name of the module, here as you are directly executing it, its being considered as a script and all scripts have the name __main__ in Python. There's a . in between because Fraction is an attribute of the script __main__ , the module; and belongs to the module level scope.
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
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