a decorating helper class that allows for optional paramaters
classParamDecorator(object):def__init__(self, decorator_function):self.func = decorator_function
def__call__(self, *args, **kwargs):iflen(args)==1andlen(kwargs)==0andcallable(args[0]):
# we're being called without paramaters# (just the decorated function)returnself.func(args[0])returnself.decorate_with(args, kwargs)defdecorate_with(self, args, kwargs):defdecorator(callable_):returnself.func(callable_, *args, **kwargs)return decorator
that's the implementation - here are a couple of examples:
@ParamDecoratordefpending(decorated, reason='no reason given'):defrun(*args, **kwargs):print"function '%s' is pending (%s)"% (decorated.__name__, reason)
return run
@ParamDecoratordeftrace(decorated, label=None):if label isNone:
label = decorated.__name__else:
label ="%s (%s)"% (decorated.__name__, label)
defrun(*args, **kwargs):print"%s: started (args=%s, kwargs=%s)"% (label, args, kwargs)
ret =decorated(*args, **kwargs)print"%s: returning: %s"% (label, ret)
return ret
return run
@pendingdefa():pass@tracedeffoo():return"blah"# NOTE: pastie gets confused by a decorator with args, and seems to show these examples with double "@" symbols. They should only have one.@@pending("I haven't done it yet!")defb():pass@@trace("important function")defbar():return"blech!"if__name__=='__main__':
a()b()foo()bar()
outputs:
# function 'a' is pending (no reason given)# function 'b' is pending (I haven't done it yet!)# foo: started (args=(), kwargs={})# foo: returning: blah# bar (important function): started (args=(), kwargs={})# bar (important function): returning: blech!