Adding a method to a function object at runtime

Posted by Carson Myers on Stack Overflow See other posts from Stack Overflow or by Carson Myers
Published on 2010-04-17T21:11:31Z Indexed on 2010/04/17 21:23 UTC
Read the original article Hit count: 182

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about function