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

前端 未结 11 1131
情话喂你
情话喂你 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:07

    You could use a decorator that tracks how many times the function is called. Since list is a built-in, you can't decorate or replace its pop method so you'd have to use your own list class, for example.

    def counted(f):
        def wrapped(*args, **kwargs):
            wrapped.calls += 1
            return f(*args, **kwargs)
        wrapped.calls = 0
        return wrapped
    
    class MyList(list):
        @counted
        def pop(self, *args, **kwargs):
            return list.pop(self, *args, **kwargs)
    
    x = MyList([1, 2, 3, 4, 5])
    for i in range(3):
        x.pop()
    
    print x.pop.calls # prints 3
    

提交回复
热议问题