Created
November 2, 2011 14:25
-
-
Save fmder/1333765 to your computer and use it in GitHub Desktop.
Count function calls decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class countCalls(object): | |
"""Decorator that keeps track of the number of times a function is called. | |
:: | |
>>> @countCalls | |
... def foo(): | |
... return "spam" | |
... | |
>>> for _ in range(10) | |
... foo() | |
... | |
>>> foo.count() | |
10 | |
>>> countCalls.counts() | |
{'foo': 10} | |
Found in the Pythod Decorator Library from http://wiki.python.org/moin web site. | |
""" | |
instances = {} | |
def __init__(self, func): | |
self.func = func | |
self.numcalls = 0 | |
countCalls.instances[f] = self | |
def __call__(self, *args, **kwargs): | |
self.numcalls += 1 | |
return self.func(*args, **kwargs) | |
def count(self): | |
"Return the number of times this function was called." | |
return countCalls.instances[self.func].numcalls | |
@staticmethod | |
def counts(): | |
"Return a dict of {function: # of calls} for all registered functions." | |
return dict([(func.__name__, countCalls.instances[func].numcalls) for func in countCalls.instances]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't line 25 say
countCalls.instances[func] = self
?