I am working on a project wherein I want to parse each line of code (present in the form of a string) in python one by one. I want the declared/updated identifiers’ id and their assigned values.
Consider a string of code here:
a = 1
a, b = 2, 0
lst = [2, 3, b]
lst[1] = 9
And I am expecting something like this after parsing each line:
{a:1}
{a:2, b:0}
{lst:[2, 3, 0]}
{(lst, 1):9}
I tried parsing the given code string using python’s ast
module. I got an abstract syntax tree as a result. Since I want the variables and their values I thought I needed the ast.Name
and ast.Constant
nodes. So, I tried iterating over the nodes in ast.walk
and checking if they are an instance of these (ast.Name
and ast.Constant
) classes. But given the complex nature of code, how do I know exactly what value is assigned to what? Also, how do I deal with code-string that has loops?
Sopan Thakre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.