Python 201: Decorating the main function

Last week, I was reading Brett Cannon’s blog where he talks about function signatures and decorating the main function. I didn’t follow everything he talked about, but I thought the concept was really interesting. The following code is an example based on a recipe that Mr. Cannon mentioned. I think it illustrates what he’s talking about, but basically if provides a way to remove the standard

if __name__ == "__main__":
   doSomething()

Anyway, here’s the code.

#----------------------------------------------------------------------
def doSomething(name="Mike"):
    """"""
    print "Welcome to the program, " + name

#----------------------------------------------------------------------
def main(f):
    """"""
    if f.__module__ == '__main__':
        f()
    return f

main(doSomething)

The nice part about this is that the main function can be anywhere in the code. If you like to use decorators, then you can re-write this as follows:

#----------------------------------------------------------------------
def main(f):
    """"""
    if f.__module__ == '__main__':
        f()
    return f

#----------------------------------------------------------------------
@main
def doSomething(name="Mike"):
    """"""
    print "Welcome to the program, " + name

Note that the main function has to come before you can decorate the doSomething function. I’m not sure how or even if I would use this sort of trick, but I thought it might be fun to experiment with at some point.

4 thoughts on “Python 201: Decorating the main function”

  1. It also has the disadvantage that doSomething has to come after every other top-level function/class/constant that it might use, since it gets executed as soon as it is defined.

  2. You might be looking for http://docs.python.org/library/functools.html#functools.wraps , or a solid CLI argument parsing script.

    One thing that bare function (or class) decorators don’t do is copy the __doc__ string over, so if you’re doing any form of documentation introspection (such as autodocumenting with Sphinx), the output may be  less than obvious.There are arguments for and against __main__ checks: http://gumption.typepad.com/blog/2012/05/def-main-in-python-considered-harmful.html

  3. I wasn’t actually looking for this functionality. I just happened to stumble upon Brett Cannon’s blog article and thought it was so stimulating and interesting that I had to write a little blurb about the concept. However, I’ll take a look at your links too. I’ll bet it’s intriguing too. Thanks!

Comments are closed.