A call graph says which function calls which. Build one for a small Python file.
What to build
A program that finds the calls between the functions of a file and the functions nobody calls.
Requirements
- A function is defined by a line that starts with
defat column 0. Its body is the following indented lines. - A call is the name of a defined function followed by
(, not preceded by a letter, digit, underscore or dot, on a line that is not a comment (a line starting with#after stripping) and not adefline. - A call inside a body counts for that function and is ignored if the function calls itself. A call on an unindented line outside any function counts only as a use.
- For each function in definition order print
NAME calls: A, Bwith the called names sorted alphabetically, orNAME calls: nothing. - Then print
never called: X, Ywith the functions that no other function and no module-level line calls, in definition order, ornever called: none.
Input
The first line has n (1 to 100). The next n lines are the code.
Output
One line per function, then the never called line.
Constraints
1 ≤ n ≤ 100.
Example
Input:
11
def read():
return "3 4"
def add(a, b):
return a + b
def main():
a, b = read().split()
print(add(int(a), int(b)))
main()
Output:
read calls: nothing
add calls: nothing
main calls: add, read
never called: none
Why it works
A first pass learns the names and a second pass attributes every call to the function whose body it sits in, which is exactly how tools build call graphs; functions with no callers are the entry points or dead code.
Examples
11
def read():
return "3 4"
def add(a, b):
return a + b
def main():
a, b = read().split()
print(add(int(a), int(b)))
main()
read calls: nothing add calls: nothing main calls: add, read never called: none
4
def helper():
pass
def unused():
helper()
helper calls: nothing unused calls: helper never called: unused
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
First pass: collect the names of all functions (lines that start with "def " at column 0).
Hint 2
Second pass: track the current function; an indented line belongs to it, a line at column 0 that is not a def is module level.
Hint 3
Use re.search(r"(?<![\w.])" + name + r"\(", line) to find a call to name.
Solution
Show one correct solution (try it yourself first)
import re
n = int(input())
lines = [input() for _ in range(n)]
names = [line[4:].split("(")[0].strip() for line in lines if line.startswith("def ")]
calls = {name: set() for name in names}
used = set()
current = None
for line in lines:
if line.startswith("def "):
current = line[4:].split("(")[0].strip()
continue
if line.strip() and not line[0].isspace():
current = None
if line.strip().startswith("#"):
continue
for name in names:
if re.search(r"(?<![\w.])" + name + r"\(", line):
if current is None:
used.add(name)
elif name != current:
calls[current].add(name)
for name in names:
called = sorted(calls[name])
print(f"{name} calls: {', '.join(called) if called else 'nothing'}")
used |= calls[name]
never = [name for name in names if name not in used]
print("never called: " + (", ".join(never) if never else "none"))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step