2

I'm trying to use ast to open a .py file and for each class in the file, give me the attributes I want.

However, I can't get ast to behave as expected.

I'd expect to be able to do

import ast

tree = ast.parse(f)
for class in tree:
    for attr in class:
        print class+" "+attr.key+"="+attr.value

For example; a bit like ElementTree with XML. Or maybe I've got the totally wrong idea behind ast, in which case, is it possible to do this another way (if not, I'll write something to do it).

joedborg
  • 17,651
  • 32
  • 84
  • 118

1 Answers1

2

A little more complex than that. You have to understand the structure of the AST and the AST node types involved. Also, use the NodeVisitor class. Try:

import ast

class MyVisitor(ast.NodeVisitor):
    def visit_ClassDef(self, node):
        body = node.body
        for statement in node.body:
            if isinstance(statement, ast.Assign):
                if len(statement.targets) == 1 and isinstance(statement.targets[0], ast.Name):
                    print 'class: %s, %s=%s' % (str(node.name), str(statement.targets[0].id), str(statement.value))

tree = ast.parse(open('path/to/your/file.py').read(), '')
MyVisitor().visit(tree)

See the docs for more detail.

beyang
  • 505
  • 3
  • 8