Build a Call graph in python including modules and functions?

前端 未结 5 1687
醉话见心
醉话见心 2020-12-07 10:46

I have a bunch of scripts to perform a task. And I really need to know the call graph of the project because it is very confusing. I am not able to execute the code because

5条回答
  •  难免孤独
    2020-12-07 11:15

    In short, no such tool exists. Python is far too dynamic of a language to be able to generate a call graph without executing the code.

    Here's some code which clearly demonstrates some of the very dynamic features of python:

    class my_obj(object):
        def __init__(self, item):
            self.item = item
        def item_to_power(self, power):
            return self.item ** power
    
    def strange_power_call(obj):
        to_call = "item_to_power"
        return getattr(obj, to_call)(4)
    
    a = eval("my" + "_obj" + "(12)")
    b = strange_power_call(a)
    

    Note that we're using eval to create an instance of my_obj and also using getattr to call one of its methods. These are both methods that would make it extremely difficult to create a static call graph for python. Additionally, there are all sorts of difficult to analyze ways of importing modules.

    I think your best bet is going to be to sit down with the code base and a pad of paper, and start taking notes by hand. This will have the dual benefit of making you more familiar with the code base, and will not be easily tricked by difficult to parse scenarios.

提交回复
热议问题