1

I'm trying to extract all variables in my code that have no indentation, here is a simple example:

import ast
import astunparse
class AnalysisNodeVisitor(ast.NodeVisitor):
    def __init__(self, nodename):
        super().__init__()
        self.nodename=nodename
        self.setVariables={}
    def visit_Assign(self,node):
        print(self.nodename,astunparse.unparse(node.targets))
        #print(ast.dump(node))

        
Analyzer=AnalysisNodeVisitor("example1")
tree=ast.parse('''\
a = 10

for i in range(10):
    b=x+i

if(x==10):
    c=36

d=20
''')
Analyzer.visit(tree)

output:

example1 a

example1 b

example1 c

example1 d

This example prints out all the 4 variables(a,b,c and d) and I'm wondering if there is a way to make it only print the assignments a,d since there is no indentation before their assignments?

I tried to dump the nodes and see if there is something I can use to filter out the variables but I can't find anything (for example it just outputs this : 'Assign(targets=[Name(id='a', ctx=Store())], value=Num(n=10))').

3
  • I haven't used that library, but assuming the AST is stored in some kind of dictionnary, you would only look for variable assignments in the first level and ignore any intermediary (deeper) node Commented Feb 8, 2021 at 17:34
  • Thank you, but if I try to dump the whole tree and print it, I get something like this "Module(body=[Assign(targets=[Name(id='a', ctx=Store())], value=Num(n=10)), For(target=Name(id='i', ctx=Store()), iter=Call(func=Name(id='range', ctx=Load()), args=[Num(n=10)], keywords=[]), body=[Assign(targets=[Name(id='b', ctx=Store())..etc" which doesn't seem to hold any information about levels or something similar. Commented Feb 8, 2021 at 17:58
  • 2
    Place this inside your visit_Assign method. print(node.col_offset) That should give you an idea of how you can manipulate it. Commented Feb 8, 2021 at 18:13

1 Answer 1

1

I think if you just look at tree.body, you can find all your top-level assignment statements.

Running this code:

import ast
import astunparse

tree=ast.parse('''\
a = 10

for i in range(10):
    b=x+i

if(x==10):
    c=36

d=20
''')

for thing in tree.body:
    if isinstance(thing, ast.Assign):
        print(astunparse.unparse(thing.targets))

Produces:


a


d

Sign up to request clarification or add additional context in comments.

1 Comment

That's actually very simple and makes a lot of sense yet I didn't think of, this answer and axe's answer mentioned in the comment above are what I'm looknig for. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.