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?
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
.)