How to implement a static variable counter inside a function using python?
import functools def count_calls(func): @functools.wraps(func) def decor(*args, **kwargs): decor.count += 1 return func(*args, **kwargs) decor.count = 0 return decor @count_calls def Func_CALL(): print Func_CALL.count for i in range(10): Func_CALL()
So the counter will print the number of times the function Func_CALL() is called.
To count the numbers of instances a class being called we can use this method.
class Foo(object): counter = 0 def __call__(self): Foo.counter += 1 print Foo.counter foo = Foo() for i in range(10): foo()