Report abuse

a decorating helper class that allows for optional paramaters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ParamDecorator(object):
    def __init__(self, decorator_function):
        self.func = decorator_function

    def __call__(self, *args, **kwargs):
        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
            # we're being called without paramaters
            # (just the decorated function)
            return self.func(args[0])
        return self.decorate_with(args, kwargs)

    def decorate_with(self, args, kwargs):
        def decorator(callable_):
            return self.func(callable_, *args, **kwargs)
        return decorator

that's the implementation - here are a couple of examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@ParamDecorator
def pending(decorated, reason='no reason given'):
    def run(*args, **kwargs):
        print "function '%s' is pending (%s)" % (decorated.__name__, reason)
    return run

@ParamDecorator
def trace(decorated, label=None):
    if label is None:
        label = decorated.__name__
    else:
        label = "%s (%s)" % (decorated.__name__, label)
    def run(*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

@pending
def a():
    pass

@trace
def foo():
    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!")
def b():
    pass

@@trace("important function")
def bar():
    return "blech!"

if __name__ == '__main__':
    a()
    b()
    foo()
    bar()

outputs:

1
2
3
4
5
6
# 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!