2

c is a parsed tree of a python code:

c=ast.parse(''' for x in y: print(x) ''')

d is the dump file of tree-c

d=ast.dump(c)

the content of d is the following string:

Module(
    body=[For(target=Name(id='x', ctx=Store()), iter=Name(id='y', ctx=Load()),
    body=[Expr(value=Call(func=Name(id='print', ctx=Load()), 
    args=[Name(id='x', ctx=Load())], keywords=[]))], orelse=[])])

I've looked around the net to see if I could find a method to use the content of d, to revert back to the tree c.

Any suggestions?

Thank you

Prune
  • 76,765
  • 14
  • 60
  • 81
alpha5401
  • 53
  • 1
  • 1
  • 5

1 Answers1

2

You can use eval to get the ast object from the string:

ast_obj = eval(d)

Then, there exist various third party libraries that can convert back to source (Given an AST, is there a working library for getting the source?, Python ast (Abstract Syntax Trees): get back source string of subnode)

Ben Jones
  • 652
  • 6
  • 21
  • Thank you! That is exactly what I was looking for. It works perfectly – alpha5401 Jul 17 '18 at 02:00
  • Are you sure this works? I get "NameError: name 'Module' is not defined" whenever I do: eval('Module(body=[For(target=Name(id='x', ctx=Store()), iter=Name(id='y', ctx=Load()),body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Name(id='x', ctx=Load())], keywords=[]))], orelse=[])])'). – berniethejet Sep 10 '20 at 03:14
  • 2
    Hi @berniethejet, yes I am sure this works. The error "NameError: name ... is not defined" usually indicates a missing import statement. In your case, try adding `from ast import *` at the top. – Ben Jones Sep 19 '20 at 06:05
  • Thanks for this @BenJones, if you hadn't told me I'd never had figured it out. But why doesn't 'import ast' work here? What does 'from ast import * ' bring in that 'import ast' misses? (Of course I had used 'import ast' when I first tried.) – berniethejet Sep 20 '20 at 03:19
  • There is a pretty big difference between 'import X' and 'from X import *': https://stackoverflow.com/questions/12270954/difference-between-import-x-and-from-x-import/12270980#12270980 – Ben Jones Sep 21 '20 at 04:10
  • Don't take this the wrong way, but I'm a little surprised you are playing with the AST without knowing import syntax/namespaces – Ben Jones Sep 21 '20 at 04:13
  • Thanks @BenJones. No offense taken. I'm teaching Mathematica to write Python via the AST, and learning Python at the same time ;). – berniethejet Sep 23 '20 at 14:45