I want to decorate a simple method, to run 5 times:
def do_5(f):
@wraps(f)
def wr(*a,**kw):
i = 0
while i < 5:
f(a,kw)
i += 1
return wr
class a(object):
@do_5
def f(self, x):
print x
however, this only makes the func print {}
where x is actually 1
Using ipdb I saw that self
is the first of *a
so I tried changing the wrapper to
In [37]: def do_5(f):
...: @wraps(f)
...: def wr(*a,**kw):
...: self, other_args = a[0], a[1:]
...: i = 0
...: while i < 5:
...: f(self,other_args,kw)
...: i += 1
...: return wr
and
In [37]: def do_5(f):
...: @wraps(f)
...: def wr(*a,**kw):
...: self, other_args = a[0], a[1:]
...: i = 0
...: while i < 5:
...: self.f(other_args,kw)
...: i += 1
...: return wr
but got:
RuntimeError: maximum recursion depth exceeded
and
TypeError: f() takes exactly 2 arguments (3 given)
respectively
How can I solve this?
BTW, can I make this decorator dynamic, as in @do_n(f, n) and decorate it like so (@do_n(100)
) and just use the n
instead of 5 in the wrapper?