POSTS
Python ast (1)
- 使用 ast.parse() 得到的 ast tree,一定都會包在 ast.Module 裡;之後重新丟回 compile 去編譯時,一樣也是要有 ast.Module 才行。
- ast.FunctionDef 裡的 name, args, body, decorator_list 必填,args 可以填 ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]) ,decorator_list 可以填空的 []
ast.dump 是好朋友,可以多加利用,看 Python 組出的 AST tree。
import ast p_node = ast.Print(values=[ast.Str(s='Hello')], nl=True) # Print 是一個特別的 node,Python 3 裡應該是不一樣的了。 f_node = ast.FunctionDef(name='foo', args=ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]), body=[p_node], decorator_list=[]) # 定義函式 e_node = ast.Expr(value=ast.Call(func=ast.Name(id='foo', ctx=ast.Load()), args=[], keywords=[], starargs=None, kwargs=None)) # 呼叫函式 m_node = ast.Module(body=[f_node, e_node]) # 放到 module 的 body 裡,body 裡是一個 list fixed = ast.fix_missing_locations(m_node) # 修正位置資訊 codeobj = compile(fixed, '', 'exec') # 編譯 eval(codeobj) # 執行 # 結果會印出 Hello # 用 dir() 觀察,也會發現多出了 foo,執行 foo() ,同樣會印出 Hello