Problem
For educational purposes, I would like to calculate how many times a given line is executed in a given function without modifying or decorating it . For example, for a function:
def binary_search(seq, x): (a, b) = (0, len(seq) - 1) while a <= b: m = (a + b) / 2 if x < seq[m]: b = m - 1 elif x > seq[m]: a = m + 1 else: return m
I would just write something like this:
print count_exec(binary_search, range(100), 44, line_number = 4)
... or even so:
print count_exec(binary_search(range(100), 44), line = "m = (a + b) / 2")
... which both should print the number of times when the 4th line is executed (which equals 7). The ultimate goal is to provide an empirical approach to the complexity of any function:

Not decisions
My current solution is to add a function attribute:
def binary_search(seq, x): binary_search.count = 0
I think I could create a decorated count_this_line function:
def binary_search(seq, x): (a, b) = (0, len(seq) - 1) while a <= b: count_this_line()
Perhaps you can decorate the binary_search function, but for me it is considered a modification of it.
Ideas
- The ast standard library can get an abstract syntax tree of any given script and even execute it.
- I have little experience using the Python profiler. I think it is very difficult for my needs. Could this be the way?