Counting the number of call of a function

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

On Fri, Sep 30, 2011 at 3:08 AM, Laurent Claessens <moky.math at> 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):
    def __call__(self,*args,**kwargs):
        print("I'm replaced!")  # if you want to be noisy

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.


More information about the Python-list mailing list