Starting from a script foo.py find all functions that are in use in local source code (i.e not built-in or third party packages), recursively.
EDIT: I do not want to find recursive functions. I want to find all functions that are in use!
e.g. foo.py
import bar
def not_used():
pass
bar.do_stuff(x,y)
bar.py
import math
def more_stuff(x,y):
result = math.abs(-x+-y)
return result
def do_stuff(x,y):
more_stuff(x,y)
Should return do_stuff & more_stuff
Should ignore not_used & abs
Many thanks
EDIT: Code so far
import dis
py_file = 'foo.py'
with open(py_file) as file:
source_code = file.read()
compiled = compile(source_code, py_file, "exec")
funcs = []
byte_code = dis.Bytecode(compiled)
instructions = list(reversed([x for x in byte_code]))
for (ix, instruction) in enumerate(instructions):
if instruction.opname == "CALL_FUNCTION":
load_func_instr = instructions[ix + instruction.arg + 1]
funcs.append(load_func_instr.argval)
results = [f'{ix}: {funcname}'for (ix, funcname) in enumerate(reversed(funcs), 1)]