How to access upstream functions called by a function in Python

21 views Asked by At

To debug a warning observed in my code, Im trying to find a way to programmatically identify the stack of functions being called by my code.

As an example

def func(x):
    return func2(x+4)

def func2(x):
    return x*3

func(5)

For the above code I want to see something like

func(5)
- func2(9)
1

There are 1 answers

0
Mark Tolonen On

pdb (and other debuggers) can do that (comments added):

C:\>py -m pdb test.py              # debug your script
> c:\test.py(1)<module>()
-> def func(x):
(Pdb) l                            # list lines around current instruction
  1  -> def func(x):
  2         return func2(x+4)
  3
  4     def func2(x):
  5         return x*3
  6
  7     func(5)
[EOF]
(Pdb) b 5                                     # breakpoint in func2 (line 5)
Breakpoint 1 at c:\users\metolone\test.py:5
(Pdb) r                                       # run to breakpoint
> c:\users\metolone\test.py(5)func2()         # in func2()
-> return x*3
(Pdb) x                                       # x (the parameter) was 9
9
(Pdb) where                                   # display call stack
  c:\dev\python312\lib\bdb.py(600)run()
-> exec(cmd, globals, locals)
  <string>(1)<module>()
  c:\users\metolone\test.py(7)<module>()
-> func(5)                                      # func(5) called
  c:\users\metolone\test.py(2)func()
-> return func2(x+4)                            # func2 called (what was x?)
> c:\users\metolone\test.py(5)func2()
-> return x*3                                   # in func2
(Pdb) x                                         # x == 9
9
(Pdb) up                                        # move up stack frame
> c:\users\metolone\test.py(2)func()
-> return func2(x+4)                            # now in func() stack frame
(Pdb) x                                         # x == 5 when about to call func2()
5

Also see the inspect module and in particular the interpreter stack for functions that can access the call stack programmatically.