After many times of writing out this default “main” code, I decided to work out if there is a way that I don’t have to type as much and make it look nicer. Yes, I’m pedantic with code neatness. Here is an example of what I’m talking about:
def main(): print 'this runs only when executed directly' if __name__ == '__main__': main()
I asked on Stack Overflow, but the general answer was “deal with it”. After a quick discussion of the problem, @dsturnbull and myself worked out that it was possible to import a module and use a decorator in place of this if statement.
The module is called automain, and here is an example of its usage:
from automain import * @automain def main(): print 'this runs only when executed directly'
How does it work?
The source code of the decorator looks like this:
def automain(func): import inspect parent = inspect.stack() name = parent.f_locals.get('__name__', None) if name == '__main__': func()
Basically it inspects the parent stack frame, and checks if __name__ is ‘__main__’, then executes the function. Otherwise it does nothing, as expected.
Interestingly enough, a random internet troll rated the module 0/5 on Python Cheese Shop and started his comment with:
spookylukey (2011-01-24, 0 points):
Seriously? Is this a joke?
1. Your implementation can’t possible work – it is going to do the same if the module is imported as a library or if it is run as a script.
All I have to say is that it does work and I find it much better to use. Thanks for the terrible and incorrect feedback though, spookylukey!