is there a way to track the number of times a function is called?

前端 未结 11 1133
情话喂你
情话喂你 2020-11-28 08:56

So i\'m trying to make a function that keeps track how many times a method is called. for example:

a = [1,2,3,4]
a.pop()

i want to know how

11条回答
  •  误落风尘
    2020-11-28 09:14

    One approach is to create a proxy of the instance for which you want to count attribute access:

    from collections import Counter
    
    class CountingProxy():
        def __init__(self, instance):
            self._instance = instance
            self.count = Counter()
    
        def __getattr__(self, key):
            if hasattr(self._instance, key):
                self.count[key] += 1
            return getattr(self._instance, key)
    
    
    >>> l = [1,2,3,4,5]
    >>> cl = CountingProxy(l)
    >>> cl.pop()
    5
    >>> cl.append(10)
    >>> cl.index(3)
    2
    >>> cl.reverse()
    >>> cl.reverse()
    >>> cl.count
    Counter({'reverse': 2, 'pop': 1, 'append': 1, 'index': 1})
    

提交回复
热议问题