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
>>>
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.
Tags: decorators, testing