Counting the number of call of a function

Chris Rebert clp2 at rebertia.com
Thu Sep 29 19:27:35 CEST 2011


On Thu, Sep 29, 2011 at 10:08 AM, Laurent Claessens <moky.math at gmail.com> 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.

That's because globals() maps names (i.e. strings) to values, whereas
in this case `fun` is a function object, not a string. Trying to
subscript globals() with a non-string arguably ought to be an error.

By way of example (with irrelevant stuff elided):

Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00)
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
...     pass
...
>>> globals()
{..., 'foo': <function foo at 0x378170>}
>>> globals()[foo] = 42
>>> globals()
{..., <function foo at 0x378170>: 42, 'foo': <function foo at 0x378170>}
>>> globals()["foo"] = 99
>>> globals()
{..., 'foo': 99, <function foo at 0x378170>: 42}

Note that you can get the name of a function using its __name__
attribute. That is to say:
foo.__name__ == "foo"

> 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_ ...

Recall that the decorator syntax:

@bar
def qux():
    pass

is basically equivalent to:

def qux():
    pass

qux = bar(qux)

Therefore, you want something like:

def wrapped(func):
    def replacement(*args, **kwargs):
        print "I'm replaced"
    return replacement

foo = wrapped(foo)
foo() # => I'm replaced

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list