Parsing Python into an instance list

I want to analyze Pure-Python code as something like a list of instances of certain classes that represent different parts of the source code.

Example:

>>> text = ''' ... for x in range(100): ... print x ... ''' >>> tree = parse(text) >>> print tree Tree( ForLoop(x,Range(100), [Stmt(Print(x))]) ) # here ForLoop, Range, Stmt, Print are all custom classes 
+4
source share
1 answer

The ast module contains the necessary tools:

 >>> import ast >>> text = ''' for x in range(100): print x ''' >>> m = ast.parse(text) >>> ast.dump(m) "Module(body=[For(target=Name(id='x', ctx=Store()), iter=Call(func=Name(id='range', ctx=Load()), args=[Num(n=100)], keywords=[], starargs=None, kwargs=None), body=[Print(dest=None, values=[Name(id='x', ctx=Load())], nl=True)], orelse=[])])" 
+4
source

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


All Articles