Welcome, guest | Sign In | My Account | Store | Cart

To be used as a decorator for a function that will maintain the number of times it was called. Here is an example use.

>>> def test():
...    print "Hello"
... 
>>> test = counter(test)
>>> test()
Hello
>>> test()
Hello
>>> test()
Hello
>>> test()
Hello
>>> test()
Hello
>>> test.invocations
5
>>> test()
Hello
>>> test.invocations
6
>>>
Python, 6 lines
1
2
3
4
5
6
    def counter(fn):
        def _counted(*largs, **kargs):
            _counted.invocations += 1
            fn(*largs, **kargs)
        _counted.invocations = 0
        return _counted

Useful to monkeypatch certain methods while testing to find out if they've been called a fixed number of times when an operation takes place.

Created by Noufal Ibrahim on Fri, 7 Jan 2011 (MIT)
Python recipes (4591)
Noufal Ibrahim's recipes (10)

Required Modules

  • (none specified)

Other Information and Tasks