Created
February 7, 2017 08:55
-
-
Save svanellewee/a6e4e8b7f52a23196c4eb3e60d7982bb to your computer and use it in GitHub Desktop.
Programmatic ast parse
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
import pprint | |
import ast | |
from ast import ClassDef, FunctionDef, Assign | |
with open("path/to/class/file.py", 'r') as supplier_file_data: | |
tree = ast.parse(supplier_file_data.read()) | |
print(dir(tree)) | |
classes = (e for e in tree.body if isinstance(e, ClassDef)) | |
def get_values(class_tree): | |
body_functions = (e.name for e in class_tree.body if isinstance(e, FunctionDef)) | |
body_assignments = (e for e in class_tree.body if isinstance(e, Assign)) | |
pretty_assignments = (e.targets[0].id for e in body_assignments if len(e.targets) == 1 and isinstance(e.targets[0], ast.Name)) | |
return {"class_name": class_tree.name, | |
"methods": list(body_functions), | |
"members": list(pretty_assignments)} | |
pprint.pprint(list(get_values(e) for e in classes)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment