pythondebuggingtrackingtracebackipdb

How to trace a function call in Python?


How do I track Python code from start to finish? That shows the entire flow of execution, from which function is called first, which operations are performed, to the end of the entire flow.

Look at this example code, it receives an operation type (addition or subtraction) and two values ​​(x and y), executes these two values ​​according to the operation and at the end displays a message:

def calc(op, x, y):
    if op == 'sum':
        return x + y
    elif op == 'subtraction':
        return x - y


def msg(op, x, y):
    if op == 'sum':
        result = calc(op, x, y)
        return "The result of the sum is: " + str(result)
    elif op == 'subtraction':
        result = calc(op, x, y)
        return "The result of the subtraction is: " + str(result)


if __name__ == '__main__':
    my_sum = msg('sum', 3, 2)
    print(my_sum)

So this "tracking from start to finish" would look something like this:

  1. Line 17: if __name__ == '__main__':
  2. Line 18: my_sum = msg('sum', 3, 2)
  3. Line 8: def msg(op, x, y):
  4. Line 9: if op == 'sum':
  5. Line 10: result = calc(op, x, y)
  6. Line 1: def calc(op, x, y):
  7. Line 2: if op == 'sum':
  8. Line 3: return x + y
  9. Line 11: return "The result of the sum is:" + str(result)
  10. Line 19: print(my_sum)

And at the end it returns the message "The result of the sum is: 5".


Solution

  • You can profile your Python script. Python itself, in the standard library, have [profilers] (https://docs.python.org/3/library/profile.html#introduction-to-the-profilers) to profile and trace your script. Also, there are a visual library called [Tuna] (https://github.com/nschloe/tuna) that can help you to graphically profile your script. Maybe, you can use another tool, to easy trace your entire script, called [KCacheGrind] (https://kcachegrind.github.io/html/Home.html), that shows a visually oriented trace of the function calls.