Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an inheritance tree from AST?

I'm using python's ast module to display a class inheritance tree.

I defined a visit_ClassDef(self, node) function for an ast.NodeVisitor, and iterate through node.bases.

However, I've been unable to get the name of the base classes as a string. So far, I've tried base.value and base.name, but to no avail.

like image 450
lowerkey Avatar asked Jan 12 '23 05:01

lowerkey


1 Answers

You're probably looking for the id attribute:

>>> import ast
>>> class Visit(ast.NodeVisitor):
...     def visit_ClassDef(self, node):
...         print [n.id for n in node.bases]
... 
>>> text = open('test.py').read()
>>> tree = ast.parse(text)
>>> Visit().visit(tree)
['Foo', 'Baz']

Here's test.py:

class Bar(Foo,Baz):
    pass

The documentation on this one is pretty tough to grok, but you can see that bases is a list of expr objects. Now it can really be any expression. You could have a function call in there:

class Bar(FooFactory(),BazFactory()): pass

and that is completely valid python. However, the typical case is that you just have identifiers (class names) which are nothing more than Name expressions. You can get the identifier's "name" as a string from the id attribute.

like image 67
mgilson Avatar answered Jan 21 '23 14:01

mgilson