Search code examples
pythongraph

Graph illustrating relations between functions


I wonder if there is a tool that is able to generate a graph illustrating relations between individual functions. For example, consider functions A(), B() and C() store in some_file.py. If function A() calls function B(), which in turn calls function C(), I would like the tool to generate a graph in a form of C() -> B() -> A().


Solution

  • That graph is called a "call graph". There are lots of tools: https://www.google.com/search?q=python+call+graph+visualization

    This function is usually built into an application called a "profiler", which can measure code performance in many ways to help you optimize. I don't know if any real profilers exist for python, because if you really care about performance then the first thing to do is switch languages.

    Profilers generate the call graph by watching your program as it runs. Of course they might not see all the function calls that are possible.

    The other way to generate a call graph is by "static analysis". These tools analyze your code without ever running it (like this one). It is impossible in principle to do this accurately, but these tools can do a pretty good job, and can find function calls that can happen, but don't happen in any particular run.