Counting the number of call of a function

MRAB python at mrabarnett.plus.com
Thu Sep 29 19:26:18 CEST 2011


On 29/09/2011 18:08, Laurent Claessens wrote:
> Hello
>
>
> Is it possible to count the number of time a function is called ?
> Of course, if I've access to the source code, it's easy.
>
> I tried the following :
>
> 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()
>
> I was hoping that globals()[foo] would be replaced by my X.replacement
> and thus the second call to foo() was expected to print "I'm replaced".
>
> Instead nothing is done.
>
> By the way, I tried to print globals() inside __init__() to see what
> happens. It turns out that the entry 'foo' is never modified.
>
> Any idea ?
> I fact what I have to do is to add a decorator _a posteriori_ ...
>
The keys of globals() are the _names_. You're giving it the function
itself.

Try this:

class wraper(object):
     def __init__(self,fun):
         globals()[fun.__name__]=self.replacement
     def replacement(*args):
         print("I'm replaced")

A decorator would be better.



More information about the Python-list mailing list