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

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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.

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

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 }}