Skip to content

Instantly share code, notes, and snippets.

@EkremDincel
Last active April 10, 2020 15:37
Show Gist options
  • Save EkremDincel/347ebe6c69bea159b3c6b68d7cb2722f to your computer and use it in GitHub Desktop.
Save EkremDincel/347ebe6c69bea159b3c6b68d7cb2722f to your computer and use it in GitHub Desktop.
An example tool for analyzing python class hierarchy statically
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