lowerkey
lowerkey

Reputation: 8335

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.

Upvotes: 5

Views: 3028

Answers (1)

mgilson
mgilson

Reputation: 309929

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.

Upvotes: 10

Related Questions