0

I have this simple python code example that parses a python code and extracts the variables assigned in it:

import ast
import sys
import astunparse
import json

tree=ast.parse('''\
a = 10
b,c=5,6
[d,e]=7,8
(f,g)=9,10
h=20
''',mode="exec")

for thing in tree.body:
    if isinstance(thing, ast.Assign):
        print(astunparse.unparse(thing).split('=')[0].strip())

I also tried a similar method with a NodeVisitor:

import ast
import sys
import astunparse
import json

tree=ast.parse('''\
a = 10
b,c=5,6
[d,e]=7,8
(f,g)=9,10
h=20
''',mode="exec")

class AnalysisNodeVisitor2(ast.NodeVisitor):
    def visit_Assign(self,node):
        print(astunparse.unparse(node.targets))
        
Analyzer=AnalysisNodeVisitor2()
Analyzer.visit(tree)

But both methods gave me this same results:

a
(b, c)
[d, e]
(f, g)
h

But the output I'm trying to get is individual variables like this:

a
b
c
d
e
f
g
h

Is there a way to achieve this?

1 Answer 1

2

Each target is either an object with an id attribute, or a sequence of targets.

for thing in tree.body:
    if isinstance(thing, ast.Assign):
        for t in thing.targets:
            try:
                print(t.id)
            except AttributeError:
                for x in t.elts:
                    print(x.id)

This, of course, doesn't handle more complicated possible assignments like a, (b, c) = [3, [4,5]], but I leave it as an exercise to write a recursive function that walks the tree, printing target names as they are found. (You may also need to adjust the code to handle things like a[3] = 5 or a.b = 10.)

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

3 Comments

Thank you for the explanation, but I just tried it and I get "AttributeError: 'Assign' object has no attribute 'elts'" at the first assignment which is the a=10 so thing in my case has neither an id attribute nor elts attribute?
Sorry, I had a working test, then tried to reproduce it here from memory and completely forgot about the targets attribute. I'll update.
Thank you very helpful.

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.