[Tutor] Counting method calls

Ricardo Aráoz ricaraoz at gmail.com
Sat Sep 22 20:37:28 CEST 2007


Kent Johnson wrote:
> One more reference:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252151
> 
> This appears as recipe 6.6 in the second edition of the printed cookbook.
> 
> Kent

Thanks Kent. I guess I got into deep waters.
It's a shame though that you can not do this in a simple manner,
considering python simplifies so many other chores.

To continue with your useful class :
class CallCounter:
     def __init__(self, delegate):
         self._delegate = delegate
         self.calls = 0
     def __getattr__(self, name):
         value = getattr(self._delegate, name)
         if callable(value):
             self.calls = getattr(self, 'calls') + 1
             print 'name:', name, 'calls:',getattr(self,'calls')
         return value

>>> a = CallCounter(list())
>>> a
name: __repr__ calls: 1
[]
>>> a
name: __repr__ calls: 2
[]
>>> name: append calls: 3    ##########
a.append(3)
name: append calls: 4

The line marked with ########## appeared as I was typing a.append so I
guess IDLE is accessing the class as I write the command in order to
display those little windows with available options.
As for PyAlaMode, it exhibits a much weirder behavior, I think I'll stop
using it.

Cheers


More information about the Tutor mailing list