この節では、Python ソースコードに対する抽象構文木 AST の かんたんな例をいくつかご紹介します。これらの例では parse() 関数をどうやって使うか、AST の repr 表現は どんなふうになっているか、そしてある AST ノードの属性に アクセスするにはどうするかを説明します。
最初のモジュールでは単一の関数を定義しています。 かりにこれは /tmp/doublelib.py に格納されていると仮定しましょう。
"""This is an example module.
This is the docstring.
"""
def double(x):
"Return twice the argument"
return x * 2
以下の対話的インタプリタのセッションでは、 見やすさのため 長い AST の repr を整形しなおしてあります。 AST の repr では qualify されていないクラス名が使われています。 repr 表現からインスタンスを作成したい場合は、 compiler.ast モジュールから それらのクラス名を import しなければなりません。
>>> import compiler
>>> mod = compiler.parseFile("/tmp/doublelib.py")
>>> mod
Module('This is an example module.\n\nThis is the docstring.\n',
Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
Stmt([Return(Mul((Name('x'), Const(2))))]))]))
>>> from compiler.ast import *
>>> Module('This is an example module.\n\nThis is the docstring.\n',
... Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
... Stmt([Return(Mul((Name('x'), Const(2))))]))]))
Module('This is an example module.\n\nThis is the docstring.\n',
Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
Stmt([Return(Mul((Name('x'), Const(2))))]))]))
>>> mod.doc
'This is an example module.\n\nThis is the docstring.\n'
>>> for node in mod.node.nodes:
... print node
...
Function('double', ['x'], [], 0, 'Return twice the argument',
Stmt([Return(Mul((Name('x'), Const(2))))]))
>>> func = mod.node.nodes[0]
>>> func.code
Stmt([Return(Mul((Name('x'), Const(2))))])
ご意見やご指摘をお寄せになりたい方は、 このドキュメントについて... をご覧ください。