I'm trying to map out the uses/causes of functions and variables in a python package at the function level. There are several modules where functions/variables are used in other functions, and I'd like to create a dictionary that looks something like:
{'function_name':{'uses': [...functions used in this function...],
'causes': [...functions that use this function...]},
...
}
The functions that I am referring to need to be defined in modules of the package.
How would I start on this? I know that I can iterate through the package __dict__
and test for functions defined in the package by doing:
import package
import inspect
import types
for name, obj in vars(package).items():
if isinstance(obj, types.FunctionType):
module, *_ = inspect.getmodule(obj).__name__.split('.')
if module == package.__name__:
# Now that function is obtained need to find usages or functions used within it
But after that I need to find the functions used within the current function. How can this be done? Is there something already developed for this type of work? I think that profiling libraries might have to do something similar to this.
The
ast
module as suggested in the comments ended up working nicely. Here is a class that I created which is used to extract the functions or variables defined in the package that are used in each function.The class can be used by first importing a python package and passing to the constructor, then calling the
build
method like so:Which will print out a dictionary containing a set of keys representing the name of a function, and values which are lists indicating the functions and or variables that are used in the function. Not every ast type is accounted for, but this was good enough in my case.
The implementation recursively breaks down nodes into simpler types until it reaches
ast.Name
after which it can extract the name of the variable, function, or method that is being used within the target function.