Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Accessing attributes of classes and methods in Python AST
-
I have written some codes to count number of attributes in classes and methods of a module but I'm not getting results. I'll be glad to get assistance. Perhaps there's something I'm doing wrongly or not doing at all. Here's the codes:
# To count the attributes in a Class and Method import ast class ClassAttributes(object): def __init__(self, node): self.node = node self.loc_in_module = 0 self.loc_in_class = 0 def get_attribute_names(self): for cls in self.node.body: if isinstance(cls, ast.ClassDef): self.loc_in_class += 1 print('Class {}'.format(self.loc_in_class)) self.loc_in_method = 0 if isinstance(cls, ast.Attribute) or isinstance(cls, ast.Assign): for target in target.targets: print('{} Atrribute: {}'.format(str(cls.lineno), target)) for node in ast.walk(cls): if isinstance(node, ast.FunctionDef): self.loc_in_method += 1 print('Method {}'.format(self.loc_in_method)) if isinstance(node, ast.Attribute) or isinstance(node, ast.Assign): for target in target.targets: print('{} Atrribute: {}'.format(str(node.lineno), target)) if __name__ == '__main__': filename = 'test.py' with open(filename, 'r') as pyfile: data = pyfile.read() pyfile.close() tree = ast.parse(data) v = ClassAttributes(tree) v.get_class_attribute_names()
-
Does not solve your problem but..
isinstance()
can take a tuple as the second parameter so...if isinstance(node, ast.Attribute) or isinstance(node, ast.Assign): pass # can be rewritten as: if isinstance(node, (ast.Attribute, ast.Assign)): pass
Also, when you
with open()
a file, you do not need to.close()
that file. -
Instead of using
ast
, you might consider usinginspect.get_members()
like in https://github.com/cclauss/Ten-lines-or-less/blob/master/platform_info.pydir()
is also usable for quick and dirty scripts.