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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With