Over a million developers have joined DZone.

Python 201: Decorating the main function

· Web Dev Zone

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.

Topics:

Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}