Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Python 201: Decorating the main function

DZone's Guide to

Python 201: Decorating the main function

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

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.

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}