Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for if __name__ == '__main__':

Tags:

python

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 :)

like image 462
gak Avatar asked Jan 23 '11 22:01

gak


People also ask

What is if__ name____ main__'?

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.

What is if __ name __ in Python?

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.

Why use__ main__ in Python?

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.

What is __ main __ class?

__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.


3 Answers

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.

like image 137
Matt Curtis Avatar answered Oct 14 '22 02:10

Matt Curtis


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.

like image 22
ThiefMaster Avatar answered Oct 14 '22 01:10

ThiefMaster


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
like image 25
gak Avatar answered Oct 14 '22 01:10

gak