1

I need to identify if a class is an extension of another class when I get into its ast node. As the parenthesis with a super-class inside does not make part of the class name I'm not being able to identify that.

if isinstance(class, ast.ClassDef):

After I know that that node I'm in is a class definition, now I need to know if this class extends another, how am I supposed to see that?

  • 1
    Possible duplicate of [How do I check (at runtime) if one class is a subclass of another?](https://stackoverflow.com/questions/4912972/how-do-i-check-at-runtime-if-one-class-is-a-subclass-of-another) – giuliano-oliveira Sep 13 '19 at 02:03

1 Answers1

0

Let's consider a simple inheritance tree

>>> src = """class C:pass\n\n\nclass D(C):pass\n\n\n"""

We can parse it and dumped the parsed source to see the overall structure:

>>> parsed = ast.parse(src)
>>> ast.dump(parsed)
"Module(body=[ClassDef(name='C', bases=[], keywords=[], body=[Pass()], 
        decorator_list=[]), ClassDef(name='D', bases=[Name(id='C', ctx=Load())],
        keywords=[], body=[Pass()], decorator_list=[])])"

We can see D is the second element in the "module" body.

>>> cd = parsed.body[1]
>>> cd.name
'D'

And we can insepct D's bases attribute to find its superclasses.

>>> cd.bases[0].id
'C'
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153