decorators.pyx 625 Bytes
Newer Older
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 42 43 44 45 46 47 48 49
__doc__ = u"""
  >>> f(1,2)
  4
  >>> f.HERE
  1

  >>> g(1,2)
  5
  >>> g.HERE
  5

  >>> h(1,2)
  6
  >>> h.HERE
  1
"""

class wrap:
    def __init__(self, func):
        self.func = func
        self.HERE = 1
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

def decorate(func):
    try:
        func.HERE += 1
    except AttributeError:
        func = wrap(func)
    return func

def decorate2(a,b):
    return decorate

@decorate
def f(a,b):
    return a+b+1

@decorate
@decorate
@decorate
@decorate
@decorate
def g(a,b):
    return a+b+2

@decorate2(1,2)
def h(a,b):
    return a+b+3