Counting the number of call of a function

Chris Angelico rosuav at gmail.com
Thu Sep 29 13:20:30 EDT 2011


On Fri, Sep 30, 2011 at 3:08 AM, Laurent Claessens <moky.math at gmail.com> wrote:
> def foo():
>    print "foo !"
>
>
> class wraper(object):
>    def __init__(self,fun):
>        globals()[fun]=self.replacement
>    def replacement(*args):
>        print "I'm replaced"
>
> foo()
> X=wraper(foo)
> foo()

Are you able to change the call structure to:

foo() # unchanged
foo=wrapper(foo) # this changes it
foo() # should now be changed

perhaps? That would be a lot easier to manage. Then you could write
the wrapper thus:

class wrapper(object):
    def __init__(self,func):
        self.func=func
    def __call__(self,*args,**kwargs):
        print("I'm replaced!")  # if you want to be noisy
        self.count+=1
        self.func(*args,**kwargs)

Tested in Python 3; should also work in Python 2, which you appear to
be using. Effectively, I've written something that could actually be a
decorator, and then done the same sort of thing that a decorator does
by rebinding the name.

ChrisA



More information about the Python-list mailing list