Last active
April 10, 2020 15:37
-
-
Save EkremDincel/347ebe6c69bea159b3c6b68d7cb2722f to your computer and use it in GitHub Desktop.
An example tool for analyzing python class hierarchy statically
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 ast | |
with open("module.py", "r") as f: # we will analysis this file | |
data = f.read() | |
tree = ast.parse(data) | |
classes = {} # {class: [parents]} | |
for i in tree.body: | |
if type(i) == ast.ClassDef: | |
classes[i.name] = [i.id for i in i.bases] # problem: can't separate classes whose are same names, you may also add path of module for fix this | |
# Another problem is class imports from other modules. | |
child_tree = {} # {class: [childs]} | |
for cls, parents in classes.items(): | |
for parent in parents: | |
child_tree.setdefault(parent, []) | |
child_tree[parent].append(cls) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment