Counting python method calls within another method

Sounds like almost the textbook example for decorators!

def counted(fn):
    def wrapper(*args, **kwargs):
        wrapper.called += 1
        return fn(*args, **kwargs)
    wrapper.called = 0
    wrapper.__name__ = fn.__name__
    return wrapper

@counted
def foo():
    return

>>> foo()
>>> foo.called
1

You could even use another decorator to automate the recording of how many times a function is called inside another function:

def counting(other):
    def decorator(fn):
        def wrapper(*args, **kwargs):
            other.called = 0
            try:
                return fn(*args, **kwargs)
            finally:
                print '%s was called %i times' % (other.__name__, other.called)
        wrapper.__name__ = fn.__name__
        return wrapper
    return decorator

@counting(foo)
def bar():
    foo()
    foo()

>>> bar()
foo was called 2 times

If foo or bar can end up calling themselves, though, you’d need a more complicated solution involving stacks to cope with the recursion. Then you’re heading towards a full-on profiler…

Possibly this wrapped decorator stuff, which tends to be used for magic, isn’t the ideal place to be looking if you’re still ‘teaching yourself Python’!

Leave a Comment