How can I determine programmatically if one function calls another function? I cannot modify either function.
Here’s what I want (source_calls_target):
>>> def check():
>>> pass
>>> def test_check():
>>> check()
>>> def source_calls_target(source, target):
>>> # if source() calls target() somewhere, return True
>>> ???
>>> source_calls_target(test_check, check)
True
>>> source_calls_target(check, test_check)
False
Ideally, I do not want to actually call target().
Ideally, I want to check if a call to target() appears within the definition for source. It may or may not actually call it depending on conditional statements.
If you can guarantee having access to the source code, you can use
ast.parse:Note that calls are always by name, so it’s difficult (and potentially impossible) to tell whether a call is to a particular function or another of the same name.
In the absence of source code, the only way is via disassembly:
The problem is that it’s in practice impossible to tell whether a function is calling another function or just loading a reference to it; if the other function is passed to
maporreduceetc. then it will be called but passed to another function it might not be. Practically the sensible thing is to assume that if the function is insource.func_code.co_namesthen it might be called: