Adding a method to a function object at runtime
- by Carson Myers
I read a question earlier asking if there was a times method in Python, that would allow a function to be called n times in a row.
Everyone suggested for _ in range(n): foo() but I wanted to try and code a different solution using a function decorator.
Here's what I have:
def times(self, n, *args, **kwargs):
for _ in range(n):
self.__call__(*args, **kwargs)
import new
def repeatable(func):
func.times = new.instancemethod(times, func, func.__class__)
@repeatable
def threeArgs(one, two, three):
print one, two, three
threeArgs.times(7, "one", two="rawr", three="foo")
When I run the program, I get the following exception:
Traceback (most recent call last):
File "", line 244, in run_nodebug
File "C:\py\repeatable.py", line 24, in
threeArgs.times(7, "one", two="rawr", three="foo")
AttributeError: 'NoneType' object has no attribute 'times'
So I suppose the decorator didn't work? How can I fix this?