Last active
June 22, 2019 06:45
-
-
Save gubser/fe423c65d28c28948551d3af86f2d934 to your computer and use it in GitHub Desktop.
Walk the abstract syntax tree to find the data dependencies of a python script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Given the python code: | |
out.p = inp.x + inp.y | |
out.q = inp.y + 1 | |
It finds these dependencies: | |
inputs are x, y | |
outputs are p, q | |
""" | |
import ast | |
import json | |
import sys | |
class DependencyFinder(ast.NodeVisitor): | |
inputs = set() | |
outputs = set() | |
def visit_Attribute(self, node): | |
if type(node.value) is ast.Name: | |
if node.value.id == 'inp': | |
self.inputs.add(node.attr) | |
elif node.value.id == 'out': | |
self.outputs.add(node.attr) | |
self.generic_visit(node) | |
if len(sys.argv) > 1: | |
finder = DependencyFinder() | |
with open(sys.argv[1], 'r', encoding='utf-8') as f: | |
code = f.read() | |
tree = ast.parse(code) | |
finder.visit(tree) | |
print("inputs are", ', '.join(sorted(finder.inputs))) | |
print("outputs are", ', '.join(sorted(finder.outputs))) | |
else: | |
print(f"usage: {sys.argv[0]} <python-file>") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment