So, I have a code snippet to count the number of function calls, and while browsing for potential optimal solutions, I came across a similar question posted here a few years ago:
is there a way to track the number of times a function is called?
One of the solutions listed in the thread above matched mine, but there was a subtle difference. When I posted my solution and asked about the potential pitfalls in my code, my comment was deleted even though mine was a solution to the question. So, I am hoping this one isn't closed as a duplicate, because frankly I don't know where to turn to.
Here was my solution:
def counter(func): counter.count=0 def wrap(*args,**kwargs): counter.count += 1 print "Number of times {} has been called so far {}".format(func.__name__,counter.count) func(*args,**kwargs) return wrap @counter def temp(name): print "Calling {}".format(name) My counter is defined as an attribute to the decorator 'counter', instead of the wrapper function 'wrap'. The code works as currently defined. But, is there a scenario where it may fail? Am I overlooking something here?
foo, call it a few million times, then define a new function afterwards namedbarand decorate that too, then your previous counts offoowill disappear.