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.

Copyright © 2024 Mouse Vs Python | Powered by Pythonlibrary