Going on this question of mine, my goal now is to parse a Python file, and to
- Extract all classes
- Extract the list of its attributes and list of bases classes
Without loading the file (running it).
Currently, I have this working code:
parser.py
import ast
def get_classes(path):
with open(path) as fh:
root = ast.parse(fh.read(), path)
classes = []
for node in ast.iter_child_nodes(root):
if isinstance(node, ast.ClassDef):
classes.append(node.name)
else:
continue
return classes
for c in get_classes('a.py'):
print(c)
File to be parsed:
from c import CClass
class MyClass(UndefinedClass):
name = 'Edgar'
def foo(self, x):
print(x)
def func():
print('Hello')
The good part of this solution is that I get the list of class names even given that file a.py contains invalid python code. Looks like I have to dig deeper into AST module. Is there any way I can extract the list of class attributes and its base classes ?