Using decorators for script tool interfaces?

822
1
05-12-2013 10:33 AM
curtvprice
MVP Esteemed Contributor
I saw a neat example this morning of Python decorators that made me think: could this be a nice way to set up a script tool interface for functions?

The way I set up tools now is as functions (so I can call them directly) and at the end of the code put something like this so I can use the file as a script tool:

if __name__ == "__main__":
  args = [arcpy.GetParameterAsText(i) for i in range(arcpy.GetParameterCount())]
  MyTool(*args)


Could this be done nicely with a decorator right above my function MyTool?
Tags (2)
0 Kudos
1 Reply
Luke_Pinner
MVP Regular Contributor
Yes, but seems a bit verbose to me. Here's a simple example using sys.argv instead of arcpy.GetParameterAsText:

import sys

def myargs(func):
    '''a decorator'''
    defaultargs =sys.argv[1:]
    def newfunc(*origargs):
        if origargs:
            return func(*origargs)
        else:
            return func(*defaultargs)
    return newfunc

@myargs #the decoration
def myfunc(*args):
    '''a decorated function'''
    return args

if __name__ == "__main__":
    for arg in myfunc('test'):print arg
    for arg in myfunc():print arg



Here's a decent explanation of decorators: http://pythonconquerstheuniverse.wordpress.com/2012/04/29/python-decorators/
0 Kudos