Easily create Python AST for multiple expressions on one line

I would like to recreate this expression with Python AST:

1 == 2; 1 >= 2 

And I can achieve this with the following AST structure:

 Module( body=[ Expr(value=Compare(left=Num(n=1), ops=[Eq()], comparators=[Num(n=2)])), Expr(value=Compare(left=Num(n=1), ops=[GtE()], comparators=[Num(n=2)])) ] ) 

But the above AST structure is identical for 2 expressions on one line and two expressions, each on a separate line.

I know that I can manually calculate and change the attributes of the col_offset and lineno nodes to make this an expression of the count line, but is there an easier way?

+5
source share
1 answer

I assume that you created AST in some other way than direct code analysis. One simple solution could be

  • convert all or parts of AST back to python code line
  • manipulate this line
  • parse() result

to get the new effective AST equivalent with the new correct row numbers and column offsets.

For example, go through the full AST and for each body , convert it to python code, replace all newline characters with a semicolon, parse() result and replace the original body with the result.

Edit: Here is a simple demo using the astunparse module:

 from ast import * from astunparse import * a1 = parse("1 == 2\n1 >= 2") print map(lambda x: (x.lineno, x.col_offset), a1.body) # [(1, 0), (2, 0)] a2 = parse(unparse(a1).strip().replace('\n', ';')) print map(lambda x: (x.lineno, x.col_offset), a2.body) # [(1, 0), (1, 9)] 
+1
source

Source: https://habr.com/ru/post/1271490/


All Articles