lima lima - 2 months ago 5
Python Question

Python: how to count the access of an instance variable

I have a python class as below.

class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------


How can I count how many time I accessed self.b variable on the invocation of meth2() or any method of class A. Is there any way, I can log the usage of self.b variable?

Answer

If you don't want to make a properly, you can log the read/write access using getattribute/setattr:

class A(object):
   def __init__(self):
       self.b_read_counter = 0
       self.b_write_counter = 0
       self.b = 12

   def __getattribute__(self,attrib):
      if attrib=="b":
          self.b_read_counter+=1

      return object.__getattribute__(self, attrib)

   def __setattr__(self,attrib,value):
      if attrib=="b":
          self.b_write_counter+=1

      return object.__setattr__(self, attrib,value)

a = A()

a.b = 23
if a.b == 34:
    print("OK")
if a.b == 34:
    print("OK")
if a.b == 34:
    print("OK")
print(a.b_read_counter)
print(a.b_write_counter)

result:

3 2

Comments