Skip to content Skip to sidebar Skip to footer

What's A Good Way To Provide Additional Decoration/metadata For Python Function Parameters?

We're considering using Python (IronPython, but I don't think that's relevant) to provide a sort of 'macro' support for another application, which controls a piece of equipment. We

Solution 1:

Decorators are a good way to add metadata to functions. Add one that takes a list of types to append to a .params property or something:

deftakes(*args):
    def_takes(fcn):
        fcn.params = args
        return fcn
    return _takes

@takes("time", "temp", "time")defdo_stuff(start_time, average_temp, stop_time):
    pass

Solution 2:

I would use some kind of decorator:

classTypeProtector(object):
    def __init__(self, fun, types):
        self.fun, self.types = fun, types
    def __call__(self, *args, **kwargs)
        # validate args with self.types
        pass
        # run function
        returnfun(*args, **kwargs)

def types(*args):
    def decorator(fun):
        # validate args count with fun parameters count
        pass
        # return covered function
        return TypeProtector(fun, args)return decorator

@types(Time, Temperature)
def myfunction(foo, bar):
    pass

myfunction('21:21', '32C')
print myfunction.types

Solution 3:

The 'pythonic' way to do this are function annotations.

defDoSomething(critical_temp: "temperature", time: "time")
    pass

Solution 4:

For python 2.x, I like to use the docstring

defmy_func(txt):
    """{
    "name": "Justin",
    "age"   :15
    }"""pass

and it can be automatically assign to the function object with this snippet

for f inglobals():
    ifnothasattr(globals()[f], '__call__'):
        continuetry:
        meta = json.loads(globals()[f].__doc__)
    except:
        continuefor k, v in meta.items():
        setattr(globals()[f], k, v)

Post a Comment for "What's A Good Way To Provide Additional Decoration/metadata For Python Function Parameters?"