python static variable counter

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()
		
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s