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 many times a.pop() was called so far so for this example, i would get 1. Is there a way to do this?
To count how many times a function has been called, declare a count variable outside of the function, setting it to 0 . Inside of the body of the function reassign the variable incrementing it by 1 . The count variable will store the number of function invocations.
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. Show activity on this post.
You could use the Performance Profiler in Visual Studio (Analyze > Performance Profiler...). In Available Tools, check Performance Wizard. Start (choose Instrumentation method).
This doesn't work for builtin functions, but an interesting approach would be:
def myfunction(): myfunction.counter += 1 myfunction.counter = 0
You're giving the function an attribute, so every call that attribute is updated. No global variables needed.
Built-ins are read-only. They cannot be modified.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With