ast —抽象構文木
ソースコード: :source: `Lib / ast.py`
ast モジュールは、PythonアプリケーションがPython抽象構文文法のツリーを処理するのに役立ちます。 抽象構文自体は、Pythonのリリースごとに変わる可能性があります。 このモジュールは、現在の文法がどのように見えるかをプログラムで見つけるのに役立ちます。
抽象構文木は、 ast.PyCF_ONLY_AST をフラグとして compile()組み込み関数に渡すか、 parse()ヘルパーを使用して生成できます。このモジュールで提供されます。 結果は、クラスがすべて ast.AST から継承するオブジェクトのツリーになります。 組み込みの compile()関数を使用して、抽象構文ツリーをPythonコードオブジェクトにコンパイルできます。
抽象文法
抽象文法は現在、次のように定義されています。
-- ASDL's 4 builtin types are:
-- identifier, int, string, constant
module Python
{
mod = Module(stmt* body, type_ignore* type_ignores)
| Interactive(stmt* body)
| Expression(expr body)
| FunctionType(expr* argtypes, expr returns)
stmt = FunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment)
| AsyncFunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
stmt* body,
expr* decorator_list)
| Return(expr? value)
| Delete(expr* targets)
| Assign(expr* targets, expr value, string? type_comment)
| AugAssign(expr target, operator op, expr value)
-- 'simple' indicates that we annotate simple name without parens
| AnnAssign(expr target, expr annotation, expr? value, int simple)
-- use 'orelse' because else is a keyword in target languages
| For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
| AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
| While(expr test, stmt* body, stmt* orelse)
| If(expr test, stmt* body, stmt* orelse)
| With(withitem* items, stmt* body, string? type_comment)
| AsyncWith(withitem* items, stmt* body, string? type_comment)
| Raise(expr? exc, expr? cause)
| Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
| Assert(expr test, expr? msg)
| Import(alias* names)
| ImportFrom(identifier? module, alias* names, int? level)
| Global(identifier* names)
| Nonlocal(identifier* names)
| Expr(expr value)
| Pass | Break | Continue
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- BoolOp() can use left & right?
expr = BoolOp(boolop op, expr* values)
| NamedExpr(expr target, expr value)
| BinOp(expr left, operator op, expr right)
| UnaryOp(unaryop op, expr operand)
| Lambda(arguments args, expr body)
| IfExp(expr test, expr body, expr orelse)
| Dict(expr* keys, expr* values)
| Set(expr* elts)
| ListComp(expr elt, comprehension* generators)
| SetComp(expr elt, comprehension* generators)
| DictComp(expr key, expr value, comprehension* generators)
| GeneratorExp(expr elt, comprehension* generators)
-- the grammar constrains where yield expressions can occur
| Await(expr value)
| Yield(expr? value)
| YieldFrom(expr value)
-- need sequences for compare to distinguish between
-- x < 4 < 3 and (x < 4) < 3
| Compare(expr left, cmpop* ops, expr* comparators)
| Call(expr func, expr* args, keyword* keywords)
| FormattedValue(expr value, int? conversion, expr? format_spec)
| JoinedStr(expr* values)
| Constant(constant value, string? kind)
-- the following expression can appear in assignment context
| Attribute(expr value, identifier attr, expr_context ctx)
| Subscript(expr value, expr slice, expr_context ctx)
| Starred(expr value, expr_context ctx)
| Name(identifier id, expr_context ctx)
| List(expr* elts, expr_context ctx)
| Tuple(expr* elts, expr_context ctx)
-- can appear only in Subscript
| Slice(expr? lower, expr? upper, expr? step)
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
expr_context = Load | Store | Del
boolop = And | Or
operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
| RShift | BitOr | BitXor | BitAnd | FloorDiv
unaryop = Invert | Not | UAdd | USub
cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn
comprehension = (expr target, expr iter, expr* ifs, int is_async)
excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,
expr* kw_defaults, arg? kwarg, expr* defaults)
arg = (identifier arg, expr? annotation, string? type_comment)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- keyword arguments supplied to call (NULL identifier for **kwargs)
keyword = (identifier? arg, expr value)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- import name with optional 'as' alias.
alias = (identifier name, identifier? asname)
withitem = (expr context_expr, expr? optional_vars)
type_ignore = TypeIgnore(int lineno, string tag)
}
ノードクラス
- class ast.AST
これは、すべてのASTノードクラスのベースです。 実際のノードクラスは、
Parser/Python.asdl
ファイルから派生しています。このファイルは以下に再現されています。 それらは_ast
Cモジュールで定義され、 ast で再エクスポートされます。抽象文法の左側の記号ごとに1つのクラスが定義されています(たとえば、
ast.stmt
またはast.expr
)。 さらに、右側のコンストラクターごとに1つのクラスが定義されています。 これらのクラスは、左側のツリーのクラスを継承します。 たとえば、 ast.BinOp はast.expr
から継承します。 代替(別名「合計」)のあるプロダクションルールの場合、左側のクラスは抽象的です。特定のコンストラクターノードのインスタンスのみが作成されます。- _fields
各具象クラスには、すべての子ノードの名前を与える属性 _fields があります。
具象クラスの各インスタンスには、文法で定義されているタイプの子ノードごとに1つの属性があります。 たとえば、 ast.BinOp インスタンスには、タイプ
ast.expr
の属性left
があります。これらの属性が文法でオプションとしてマークされている場合(疑問符を使用)、値は
None
である可能性があります。 属性が0個以上の値(アスタリスクでマークされている)を持つことができる場合、値はPythonリストとして表されます。 compile()を使用してASTをコンパイルするときは、すべての可能な属性が存在し、有効な値を持っている必要があります。
- lineno
col_offset
end_lineno
end_col_offset ast.expr
およびast.stmt
サブクラスのインスタンスには、 lineno 、 col_offset 、 end_lineno 、および end_col_offset 属性があります。 。 lineno と end_lineno は、ソーステキストスパンの最初と最後の行番号(1-インデックスが付けられているため、最初の行は1行目)であり、 col_offset および end_col_offset は、ノードを生成した最初と最後のトークンの対応するUTF-8バイトオフセットです。 パーサーはUTF-8を内部で使用するため、UTF-8オフセットが記録されます。終了位置はコンパイラーによって必須ではないため、オプションであることに注意してください。 終了オフセットは、最後のシンボルの後です。たとえば、
source_line[node.col_offset : node.end_col_offset]
を使用して1行の式ノードのソースセグメントを取得できます。
クラス
ast.T
のコンストラクターは、その引数を次のように解析します。位置引数がある場合は、
T._fields
の項目と同じ数でなければなりません。 これらの名前の属性として割り当てられます。キーワード引数がある場合、それらは同じ名前の属性を指定された値に設定します。
たとえば、 ast.UnaryOp ノードを作成してデータを入力するには、次のように使用できます。
node = ast.UnaryOp() node.op = ast.USub() node.operand = ast.Constant() node.operand.value = 5 node.operand.lineno = 0 node.operand.col_offset = 0 node.lineno = 0 node.col_offset = 0
またはよりコンパクト
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0), lineno=0, col_offset=0)
バージョン3.8で変更:クラス ast.Constant がすべての定数に使用されるようになりました。
バージョン3.9で変更:単純なインデックスはその値で表され、拡張スライスはタプルで表されます。
バージョン3.8以降非推奨:古いクラスast.Num
、ast.Str
、ast.Bytes
、ast.NameConstant
、ast.Ellipsis
は引き続き利用可能、ただし、将来のPythonリリースで削除される予定です。 それまでの間、それらをインスタンス化すると、別のクラスのインスタンスが返されます。
バージョン3.9以降非推奨:古いクラスast.Index
およびast.ExtSlice
は引き続き使用できますが、将来のPythonリリースで削除される予定です。 それまでの間、それらをインスタンス化すると、別のクラスのインスタンスが返されます。
リテラル
- class ast.Constant(value)
定数値。
Constant
リテラルのvalue
属性には、それが表すPythonオブジェクトが含まれています。 表示される値は、数値、文字列、None
などの単純なタイプだけでなく、すべての要素が定数の場合は不変のコンテナータイプ(タプルとフリーズセット)でもかまいません。>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) Expression( body=Constant(value=123))
- class ast.FormattedValue(value, conversion, format_spec)
- f文字列の単一のフォーマットフィールドを表すノード。 文字列に単一のフォーマットフィールドが含まれ、他にノードを分離できない場合は、 JoinedStr に表示されます。
value
は、任意の式ノード(リテラル、変数、関数呼び出しなど)です。conversion
は整数です:
- -1:フォーマットなし
- 115:
!s
文字列のフォーマット - 114:
!r
reprフォーマット - 97:
!a
ASCIIフォーマット
format_spec
は、値のフォーマットを表す JoinedStr ノード、またはフォーマットが指定されていない場合はNone
です。conversion
とformat_spec
の両方を同時に設定できます。
- class ast.JoinedStr(values)
一連の FormattedValue ノードと Constant ノードで構成されるf文字列。
>>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4)) Expression( body=JoinedStr( values=[ Constant(value='sin('), FormattedValue( value=Name(id='a', ctx=Load()), conversion=-1), Constant(value=') is '), FormattedValue( value=Call( func=Name(id='sin', ctx=Load()), args=[ Name(id='a', ctx=Load())], keywords=[]), conversion=-1, format_spec=JoinedStr( values=[ Constant(value='.3')]))]))
- class ast.List(elts, ctx)
class ast.Tuple(elts, ctx) リストまたはタプル。
elts
は、要素を表すノードのリストを保持します。 コンテナが割り当てターゲットの場合、ctx
は Store です(つまり、(x,y)=something
)、それ以外の場合は Load 。>>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4)) Expression( body=List( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)], ctx=Load())) >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4)) Expression( body=Tuple( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)], ctx=Load()))
- class ast.Set(elts)
セット。
elts
は、セットの要素を表すノードのリストを保持します。>>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4)) Expression( body=Set( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)]))
- class ast.Dict(keys, values)
辞書。
keys
とvalues
は、それぞれキーと値を表すノードのリストを一致する順序で保持します(dictionary.keys()
とdictionary.values()
を呼び出すと返されるもの)。辞書リテラルを使用して辞書の解凍を行う場合、展開される式は
values
リストにあり、None
はkeys
の対応する位置にあります。>>> print(ast.dump(ast.parse('{"a":1, **d}', mode='eval'), indent=4)) Expression( body=Dict( keys=[ Constant(value='a'), None], values=[ Constant(value=1), Name(id='d', ctx=Load())]))
変数
- class ast.Name(id, ctx)
- 変数名。
id
は名前を文字列として保持し、ctx
は次のいずれかのタイプです。
- class ast.Load
class ast.Store
class ast.Del 変数参照を使用して、変数の値をロードしたり、新しい値を割り当てたり、削除したりできます。 変数参照には、これらのケースを区別するためのコンテキストが与えられます。
>>> print(ast.dump(ast.parse('a'), indent=4)) Module( body=[ Expr( value=Name(id='a', ctx=Load()))], type_ignores=[]) >>> print(ast.dump(ast.parse('a = 1'), indent=4)) Module( body=[ Assign( targets=[ Name(id='a', ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>> print(ast.dump(ast.parse('del a'), indent=4)) Module( body=[ Delete( targets=[ Name(id='a', ctx=Del())])], type_ignores=[])
- class ast.Starred(value, ctx)
*var
変数参照。value
は変数、通常は Name ノードを保持します。 このタイプは、*args
を使用して Call ノードを構築するときに使用する必要があります。>>> print(ast.dump(ast.parse('a, *b = it'), indent=4)) Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Starred( value=Name(id='b', ctx=Store()), ctx=Store())], ctx=Store())], value=Name(id='it', ctx=Load()))], type_ignores=[])
式
- class ast.Expr(value)
関数呼び出しなどの式が、戻り値が使用または保存されていないステートメントとして単独で表示される場合、このコンテナーにラップされます。
value
は、このセクションの他のノードの1つ、定数、名前、ラムダ、歩留まりを保持します。 ]または YieldFrom ノード。>>> print(ast.dump(ast.parse('-a'), indent=4)) Module( body=[ Expr( value=UnaryOp( op=USub(), operand=Name(id='a', ctx=Load())))], type_ignores=[])
- class ast.UnaryOp(op, operand)
- 単項演算。
op
は演算子であり、operand
は任意の式ノードです。
- class ast.UAdd
class ast.USub
class ast.Not
class ast.Invert 単項演算子トークン。 Not は
not
キーワード、 Invert は~
演算子です。>>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4)) Expression( body=UnaryOp( op=Not(), operand=Name(id='x', ctx=Load())))
- class ast.BinOp(left, op, right)
二項演算(加算や除算など)。
op
は演算子であり、left
とright
は任意の式ノードです。>>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4)) Expression( body=BinOp( left=Name(id='x', ctx=Load()), op=Add(), right=Name(id='y', ctx=Load())))
- class ast.Add
class ast.Sub
class ast.Mult
class ast.Div
class ast.FloorDiv
class ast.Mod
class ast.Pow
class ast.LShift
class ast.RShift
class ast.BitOr
class ast.BitXor
class ast.BitAnd
class ast.MatMult
- 二項演算子トークン。
- class ast.BoolOp(op, values)
ブール演算、「または」または「および」。
op
はまたはまたはおよびです。values
は関連する値です。a or b or c
など、同じ演算子を使用した連続した操作は、複数の値を持つ1つのノードにまとめられます。これには、 UnaryOp である
not
は含まれません。>>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4)) Expression( body=BoolOp( op=Or(), values=[ Name(id='x', ctx=Load()), Name(id='y', ctx=Load())]))
- class ast.And
class ast.Or
- ブール演算子トークン。
- class ast.Compare(left, ops, comparators)
2つ以上の値の比較。
left
は比較の最初の値、ops
は演算子のリスト、comparators
は比較の最初の要素の後の値のリストです。>>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4)) Expression( body=Compare( left=Constant(value=1), ops=[ LtE(), Lt()], comparators=[ Name(id='a', ctx=Load()), Constant(value=10)]))
- class ast.Eq
class ast.NotEq
class ast.Lt
class ast.LtE
class ast.Gt
class ast.GtE
class ast.Is
class ast.IsNot
class ast.In
class ast.NotIn
- 比較演算子トークン。
- class ast.Call(func, args, keywords, starargs, kwargs)
関数呼び出し。
func
は関数であり、多くの場合、 Name または Attribute オブジェクトになります。 議論の:args
は、位置によって渡される引数のリストを保持します。keywords
は、キーワードによって渡された引数を表すキーワードオブジェクトのリストを保持します。
Call
ノードを作成する場合、args
とkeywords
が必要ですが、空のリストにすることもできます。starargs
およびkwargs
はオプションです。>>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4)) Expression( body=Call( func=Name(id='func', ctx=Load()), args=[ Name(id='a', ctx=Load()), Starred( value=Name(id='d', ctx=Load()), ctx=Load())], keywords=[ keyword( arg='b', value=Name(id='c', ctx=Load())), keyword( value=Name(id='e', ctx=Load()))]))
- class ast.keyword(arg, value)
- 関数呼び出しまたはクラス定義へのキーワード引数。
arg
はパラメーター名の生の文字列であり、value
は渡すノードです。
- class ast.IfExp(test, body, orelse)
a if b else c
などの式。 各フィールドは単一のノードを保持するため、次の例では、3つすべてが Name ノードです。>>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4)) Expression( body=IfExp( test=Name(id='b', ctx=Load()), body=Name(id='a', ctx=Load()), orelse=Name(id='c', ctx=Load())))
- class ast.Attribute(value, attr, ctx)
属性アクセス、例:
d.keys
。value
はノードであり、通常は Name です。attr
は属性の名前を示す裸の文字列であり、ctx
は Load 、 Store 、または Del です。属性がどのように作用するか。>>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4)) Expression( body=Attribute( value=Name(id='snake', ctx=Load()), attr='colour', ctx=Load()))
- class ast.NamedExpr(target, value)
名前付き式。 このASTノードは、代入式演算子(セイウチ演算子とも呼ばれます)によって生成されます。 最初の引数を複数のノードにすることができる Assign ノードとは対照的に、この場合、
target
とvalue
の両方が単一ノードである必要があります。>>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4)) Expression( body=NamedExpr( target=Name(id='x', ctx=Store()), value=Constant(value=4)))
添え字
- class ast.Subscript(value, slice, ctx)
l[1]
などの添え字。value
は、添え字付きのオブジェクト(通常はシーケンスまたはマッピング)です。slice
は、インデックス、スライス、またはキーです。 タプルにすることができ、スライスを含めることができます。ctx
は、添え字で実行されたアクションに応じて、 Load 、 Store 、または Del です。>>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4)) Expression( body=Subscript( value=Name(id='l', ctx=Load()), slice=Tuple( elts=[ Slice( lower=Constant(value=1), upper=Constant(value=2)), Constant(value=3)], ctx=Load()), ctx=Load()))
- class ast.Slice(lower, upper, step)
通常のスライス(
lower:upper
またはlower:upper:step
の形式)。 Subscript の slice フィールド内でのみ、直接または Tuple の要素として発生する可能性があります。>>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4)) Expression( body=Subscript( value=Name(id='l', ctx=Load()), slice=Slice( lower=Constant(value=1), upper=Constant(value=2)), ctx=Load()))
内包表記
- class ast.ListComp(elt, generators)
class ast.SetComp(elt, generators)
class ast.GeneratorExp(elt, generators)
class ast.DictComp(key, value, generators) 内包表記、ジェネレータ式、および辞書内包表記を一覧表示して設定します。
elt
(またはkey
およびvalue
)は、各アイテムについて評価されるパーツを表す単一のノードです。generators
は、理解ノードのリストです。>>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4)) Expression( body=ListComp( elt=Name(id='x', ctx=Load()), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers', ctx=Load()), ifs=[], is_async=0)])) >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4)) Expression( body=DictComp( key=Name(id='x', ctx=Load()), value=BinOp( left=Name(id='x', ctx=Load()), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers', ctx=Load()), ifs=[], is_async=0)])) >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4)) Expression( body=SetComp( elt=Name(id='x', ctx=Load()), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers', ctx=Load()), ifs=[], is_async=0)]))
- class ast.comprehension(target, iter, ifs, is_async)
理解の1つの
for
句。target
は、各要素に使用する参照です。通常は、 Name または Tuple ノードです。iter
は、反復するオブジェクトです。ifs
は、テスト式のリストです。各for
句には、複数のifs
を含めることができます。is_async
は、理解が非同期であることを示します(for
の代わりにasync for
を使用)。 値は整数(0または1)です。>>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'), ... indent=4)) # Multiple comprehensions in one. Expression( body=ListComp( elt=Call( func=Name(id='ord', ctx=Load()), args=[ Name(id='c', ctx=Load())], keywords=[]), generators=[ comprehension( target=Name(id='line', ctx=Store()), iter=Name(id='file', ctx=Load()), ifs=[], is_async=0), comprehension( target=Name(id='c', ctx=Store()), iter=Name(id='line', ctx=Load()), ifs=[], is_async=0)])) >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'), ... indent=4)) # generator comprehension Expression( body=GeneratorExp( elt=BinOp( left=Name(id='n', ctx=Load()), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='n', ctx=Store()), iter=Name(id='it', ctx=Load()), ifs=[ Compare( left=Name(id='n', ctx=Load()), ops=[ Gt()], comparators=[ Constant(value=5)]), Compare( left=Name(id='n', ctx=Load()), ops=[ Lt()], comparators=[ Constant(value=10)])], is_async=0)])) >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'), ... indent=4)) # Async comprehension Expression( body=ListComp( elt=Name(id='i', ctx=Load()), generators=[ comprehension( target=Name(id='i', ctx=Store()), iter=Name(id='soc', ctx=Load()), ifs=[], is_async=1)]))
ステートメント
- class ast.Assign(targets, value, type_comment)
仕事、宿題。
targets
はノードのリストであり、value
は単一ノードです。targets
の複数のノードは、それぞれに同じ値を割り当てることを表します。 解凍は、タプルまたはリストをtargets
内に配置することで表されます。- type_comment
type_comment
は、コメントとして型注釈が付いたオプションの文字列です。
>>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment Module( body=[ Assign( targets=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], ctx=Store())], value=Name(id='c', ctx=Load()))], type_ignores=[])
- class ast.AnnAssign(target, annotation, value, simple)
型注釈付きの割り当て。
target
は単一ノードであり、名前、属性、または添え字にすることができます。annotation
は、 Constant または Name ノードなどの注釈です。value
は単一のオプションノードです。simple
は、target
の Name ノードに対してTrueに設定されたブール整数であり、括弧の間に表示されないため、純粋な名前であり、式ではありません。>>> print(ast.dump(ast.parse('c: int'), indent=4)) Module( body=[ AnnAssign( target=Name(id='c', ctx=Store()), annotation=Name(id='int', ctx=Load()), simple=1)], type_ignores=[]) >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis Module( body=[ AnnAssign( target=Name(id='a', ctx=Store()), annotation=Name(id='int', ctx=Load()), value=Constant(value=1), simple=0)], type_ignores=[]) >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation Module( body=[ AnnAssign( target=Attribute( value=Name(id='a', ctx=Load()), attr='b', ctx=Store()), annotation=Name(id='int', ctx=Load()), simple=0)], type_ignores=[]) >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation Module( body=[ AnnAssign( target=Subscript( value=Name(id='a', ctx=Load()), slice=Constant(value=1), ctx=Store()), annotation=Name(id='int', ctx=Load()), simple=0)], type_ignores=[])
- class ast.AugAssign(target, op, value)
a += 1
などの拡張割り当て。 次の例では、target
はx
の Name ノード( Store コンテキストを使用)、op
はです。 ] Add 、およびvalue
は、値が1の Constant です。target
属性は、 Assign のターゲットとは異なり、クラス Tuple または List ではありません。>>> print(ast.dump(ast.parse('x += 2'), indent=4)) Module( body=[ AugAssign( target=Name(id='x', ctx=Store()), op=Add(), value=Constant(value=2))], type_ignores=[])
- class ast.Raise(exc, cause)
raise
ステートメント。exc
は発生する例外オブジェクトであり、通常は Call または Name 、またはスタンドアロンraise
の場合はNone
です。cause
は、raise x from y
のy
のオプションパーツです。>>> print(ast.dump(ast.parse('raise x from y'), indent=4)) Module( body=[ Raise( exc=Name(id='x', ctx=Load()), cause=Name(id='y', ctx=Load()))], type_ignores=[])
- class ast.Assert(test, msg)
アサーション。
test
は、 Compare ノードなどの条件を保持します。msg
は失敗メッセージを保持します。>>> print(ast.dump(ast.parse('assert x,y'), indent=4)) Module( body=[ Assert( test=Name(id='x', ctx=Load()), msg=Name(id='y', ctx=Load()))], type_ignores=[])
- class ast.Delete(targets)
del
ステートメントを表します。targets
は、 Name 、 Attribute 、 Subscript ノードなどのノードのリストです。>>> print(ast.dump(ast.parse('del x,y,z'), indent=4)) Module( body=[ Delete( targets=[ Name(id='x', ctx=Del()), Name(id='y', ctx=Del()), Name(id='z', ctx=Del())])], type_ignores=[])
- class ast.Pass
pass
ステートメント。>>> print(ast.dump(ast.parse('pass'), indent=4)) Module( body=[ Pass()], type_ignores=[])
関数またはループ内でのみ適用可能なその他のステートメントについては、他のセクションで説明します。
輸入
- class ast.Import(names)
インポートステートメント。
names
は、エイリアスノードのリストです。>>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) Module( body=[ Import( names=[ alias(name='x'), alias(name='y'), alias(name='z')])], type_ignores=[])
- class ast.ImportFrom(module, names, level)
from x import y
を表します。module
は、先頭のドットを含まない「from」名の生の文字列です。from . import foo
などのステートメントの場合はNone
です。level
は、相対インポートのレベルを保持する整数です(0は絶対インポートを意味します)。>>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4)) Module( body=[ ImportFrom( module='y', names=[ alias(name='x'), alias(name='y'), alias(name='z')], level=0)], type_ignores=[])
- class ast.alias(name, asname)
両方のパラメーターは、名前の生の文字列です。 通常の名前を使用する場合は、
asname
をNone
にすることができます。>>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4)) Module( body=[ ImportFrom( module='foo.bar', names=[ alias(name='a', asname='b'), alias(name='c')], level=2)], type_ignores=[])
制御フロー
ノート
else
などのオプションの句は、存在しない場合は空のリストとして保存されます。
- class ast.If(test, body, orelse)
if
ステートメント。test
は、 Compare ノードなどの単一ノードを保持します。body
とorelse
はそれぞれノードのリストを保持します。elif
句は、ASTで特別な表現を持っていませんが、前のorelse
セクション内の余分な If ノードとして表示されます。>>> print(ast.dump(ast.parse(""" ... if x: ... ... ... elif y: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ If( test=Name(id='x', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ If( test=Name(id='y', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[])
- class ast.For(target, iter, body, orelse, type_comment)
for
ループ。target
は、ループが割り当てる変数を、単一の Name 、 Tuple 、または List ノードとして保持します。iter
は、ループされるアイテムを1つのノードとして保持します。body
およびorelse
には、実行するノードのリストが含まれています。orelse
にあるものは、break
ステートメントではなく、ループが正常に終了した場合に実行されます。- type_comment
type_comment
は、コメントとして型注釈が付いたオプションの文字列です。
>>> print(ast.dump(ast.parse(""" ... for x in y: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ For( target=Name(id='x', ctx=Store()), iter=Name(id='y', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[])
- class ast.While(test, body, orelse)
while
ループ。test
は、 Compare ノードなどの条件を保持します。>> print(ast.dump(ast.parse(""" ... while x: ... ... ... else: ... ... ... """), indent=4)) Module( body=[ While( test=Name(id='x', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[])
- class ast.Break
class ast.Continue break
およびcontinue
ステートメント。>>> print(ast.dump(ast.parse("""\ ... for a in b: ... if a > 5: ... break ... else: ... continue ... ... """), indent=4)) Module( body=[ For( target=Name(id='a', ctx=Store()), iter=Name(id='b', ctx=Load()), body=[ If( test=Compare( left=Name(id='a', ctx=Load()), ops=[ Gt()], comparators=[ Constant(value=5)]), body=[ Break()], orelse=[ Continue()])], orelse=[])], type_ignores=[])
- class ast.Try(body, handlers, orelse, finalbody)
try
ブロック。 ExceptHandler ノードのリストであるhandlers
を除いて、すべての属性は実行するノードのリストです。>>> print(ast.dump(ast.parse(""" ... try: ... ... ... except Exception: ... ... ... except OtherException as e: ... ... ... else: ... ... ... finally: ... ... ... """), indent=4)) Module( body=[ Try( body=[ Expr( value=Constant(value=Ellipsis))], handlers=[ ExceptHandler( type=Name(id='Exception', ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))]), ExceptHandler( type=Name(id='OtherException', ctx=Load()), name='e', body=[ Expr( value=Constant(value=Ellipsis))])], orelse=[ Expr( value=Constant(value=Ellipsis))], finalbody=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[])
- class ast.ExceptHandler(type, name, body)
単一の
except
句。type
は、一致する例外タイプであり、通常は Name ノード(またはキャッチオールexcept:
句の場合はNone
)です。name
は、例外を保持する名前の生の文字列です。句にas foo
がない場合は、None
です。body
はノードのリストです。>>> print(ast.dump(ast.parse("""\ ... try: ... a + 1 ... except TypeError: ... pass ... """), indent=4)) Module( body=[ Try( body=[ Expr( value=BinOp( left=Name(id='a', ctx=Load()), op=Add(), right=Constant(value=1)))], handlers=[ ExceptHandler( type=Name(id='TypeError', ctx=Load()), body=[ Pass()])], orelse=[], finalbody=[])], type_ignores=[])
- class ast.With(items, body, type_comment)
with
ブロック。items
は、コンテキストマネージャーを表す withitem ノードのリストであり、body
は、コンテキスト内のインデントされたブロックです。
- type_comment
type_comment
は、コメントとして型注釈が付いたオプションの文字列です。
- class ast.withitem(context_expr, optional_vars)
with
ブロック内の単一のコンテキストマネージャー。context_expr
はコンテキストマネージャーであり、多くの場合 Call ノードです。optional_vars
は、as foo
パーツの名前、タプルまたはリスト、またはその場合はNone
です。使用されていません。>>> print(ast.dump(ast.parse("""\ ... with a as b, c as d: ... something(b, d) ... """), indent=4)) Module( body=[ With( items=[ withitem( context_expr=Name(id='a', ctx=Load()), optional_vars=Name(id='b', ctx=Store())), withitem( context_expr=Name(id='c', ctx=Load()), optional_vars=Name(id='d', ctx=Store()))], body=[ Expr( value=Call( func=Name(id='something', ctx=Load()), args=[ Name(id='b', ctx=Load()), Name(id='d', ctx=Load())], keywords=[]))])], type_ignores=[])
関数とクラスの定義
- class ast.FunctionDef(name, args, body, decorator_list, returns, type_comment)
関数定義。
name
は、関数名の生の文字列です。args
は arguments ノードです。body
は、関数内のノードのリストです。decorator_list
は、適用されるデコレータのリストであり、最も外側に格納されます(つまり、 リストの最初のものが最後に適用されます)。returns
はリターンアノテーションです。
- type_comment
type_comment
は、コメントとして型注釈が付いたオプションの文字列です。
- class ast.Lambda(args, body)
lambda
は、式内で使用できる最小限の関数定義です。 FunctionDef とは異なり、body
は単一のノードを保持します。>>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4)) Module( body=[ Expr( value=Lambda( args=arguments( posonlyargs=[], args=[ arg(arg='x'), arg(arg='y')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=Constant(value=Ellipsis)))], type_ignores=[])
- class ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)
- 関数の引数。
- class ast.arg(arg, annotation, type_comment)
リスト内の単一の引数。
arg
は引数名の生の文字列であり、annotation
は、Str
または Name ノードなどの注釈です。- type_comment
type_comment
は、コメントとして型注釈が付いたオプションの文字列です
>>> print(ast.dump(ast.parse("""\ ... @decorator1 ... @decorator2 ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation': ... pass ... """), indent=4)) Module( body=[ FunctionDef( name='f', args=arguments( posonlyargs=[], args=[ arg( arg='a', annotation=Constant(value='annotation')), arg(arg='b'), arg(arg='c')], vararg=arg(arg='d'), kwonlyargs=[ arg(arg='e'), arg(arg='f')], kw_defaults=[ None, Constant(value=3)], kwarg=arg(arg='g'), defaults=[ Constant(value=1), Constant(value=2)]), body=[ Pass()], decorator_list=[ Name(id='decorator1', ctx=Load()), Name(id='decorator2', ctx=Load())], returns=Constant(value='return annotation'))], type_ignores=[])
- class ast.Return(value)
return
ステートメント。>>> print(ast.dump(ast.parse('return 4'), indent=4)) Module( body=[ Return( value=Constant(value=4))], type_ignores=[])
- class ast.Yield(value)
class ast.YieldFrom(value) yield
またはyield from
式。 これらは式であるため、返送された値が使用されない場合は、 Expr ノードでラップする必要があります。>>> print(ast.dump(ast.parse('yield x'), indent=4)) Module( body=[ Expr( value=Yield( value=Name(id='x', ctx=Load())))], type_ignores=[]) >>> print(ast.dump(ast.parse('yield from x'), indent=4)) Module( body=[ Expr( value=YieldFrom( value=Name(id='x', ctx=Load())))], type_ignores=[])
- class ast.Global(names)
class ast.Nonlocal(names) global
およびnonlocal
ステートメント。names
は生の文字列のリストです。>>> print(ast.dump(ast.parse('global x,y,z'), indent=4)) Module( body=[ Global( names=[ 'x', 'y', 'z'])], type_ignores=[]) >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) Module( body=[ Nonlocal( names=[ 'x', 'y', 'z'])], type_ignores=[])
- class ast.ClassDef(name, bases, keywords, starargs, kwargs, body, decorator_list)
クラス定義。
name
は、クラス名の生の文字列ですbases
は、明示的に指定された基本クラスのノードのリストです。keywords
は、主に「メタクラス」用のキーワードノードのリストです。 PEP-3115 に従って、他のキーワードがメタクラスに渡されます。starargs
とkwargs
は、関数呼び出しの場合と同様に、それぞれ単一のノードです。 starargsは基本クラスのリストに参加するように展開され、kwargsはメタクラスに渡されます。body
は、クラス定義内のコードを表すノードのリストです。decorator_list
は、 FunctionDef と同様に、ノードのリストです。
>>> print(ast.dump(ast.parse("""\ ... @decorator1 ... @decorator2 ... class Foo(base1, base2, metaclass=meta): ... pass ... """), indent=4)) Module( body=[ ClassDef( name='Foo', bases=[ Name(id='base1', ctx=Load()), Name(id='base2', ctx=Load())], keywords=[ keyword( arg='metaclass', value=Name(id='meta', ctx=Load()))], body=[ Pass()], decorator_list=[ Name(id='decorator1', ctx=Load()), Name(id='decorator2', ctx=Load())])], type_ignores=[])
非同期して待つ
- class ast.AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment)
async def
関数の定義。 FunctionDef と同じフィールドがあります。
- class ast.Await(value)
await
式。value
はそれが待つものです。 AsyncFunctionDef の本体でのみ有効です。
>>> print(ast.dump(ast.parse("""\
... async def f():
... await other_func()
... """), indent=4))
Module(
body=[
AsyncFunctionDef(
name='f',
args=arguments(
posonlyargs=[],
args=[],
kwonlyargs=[],
kw_defaults=[],
defaults=[]),
body=[
Expr(
value=Await(
value=Call(
func=Name(id='other_func', ctx=Load()),
args=[],
keywords=[])))],
decorator_list=[])],
type_ignores=[])
- class ast.AsyncFor(target, iter, body, orelse, type_comment)
class ast.AsyncWith(items, body, type_comment)
async for
ループとasync with
コンテキストマネージャー。 それぞれ For および With と同じフィールドがあります。 AsyncFunctionDef の本体でのみ有効です。
ノート
文字列が ast.parse()によって解析される場合、演算子ノード(ast.operator
、ast.unaryop
、ast.cmpop
、ast.boolop
のサブクラス返されるツリーのast.expr_context
)はシングルトンになります。 1つへの変更は、同じ値の他のすべてのオカレンスに反映されます(例: ast.Add )。
ast ヘルパー
ノードクラスとは別に、 ast モジュールは、抽象構文木をトラバースするためのこれらのユーティリティ関数とクラスを定義します。
- ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)
ソースをASTノードに解析します。
compile(source, filename, mode, ast.PyCF_ONLY_AST)
と同等です。type_comments=True
が指定されている場合、パーサーは、 PEP 484 および PEP 526 [で指定されたタイプコメントをチェックして返すように変更されます。 X146X]。 これは、 compile()に渡されるフラグに ast.PyCF_TYPE_COMMENTS を追加することと同じです。 これにより、タイプコメントの置き忘れの構文エラーが報告されます。 このフラグがないと、タイプコメントは無視され、選択したASTノードのtype_comment
フィールドは常にNone
になります。 さらに、# type: ignore
コメントの場所は、Module
のtype_ignores
属性として返されます(それ以外の場合は、常に空のリストです)。さらに、
mode
が'func_type'
の場合、入力構文は PEP 484 の「署名タイプのコメント」に対応するように変更されます。(str, int) -> List[str]
。また、
feature_version
をタプル(major, minor)
に設定すると、そのPythonバージョンの文法を使用して解析が試行されます。 現在、major
は3
と等しくなければなりません。 たとえば、feature_version=(3, 4)
を設定すると、変数名としてasync
とawait
を使用できるようになります。 サポートされている最低バージョンは(3, 4)
です。 最高はsys.version_info[0:2]
です。ソースにヌル文字( '0')が含まれている場合、 ValueError が発生します。
警告
ソースコードをASTオブジェクトに正常に解析しても、提供されたソースコードが、コンパイルステップでさらに SyntaxError 例外が発生する可能性があるため実行できる有効なPythonコードであるとは限らないことに注意してください。 たとえば、ソース
return 42
はreturnステートメントの有効なASTノードを生成しますが、単独でコンパイルすることはできません(関数ノード内にある必要があります)。特に、 ast.parse()は、コンパイルステップで行われるスコープチェックを行いません。
警告
PythonのASTコンパイラではスタックの深さが制限されているため、十分に大きい/複雑な文字列でPythonインタプリタがクラッシュする可能性があります。
バージョン3.8で変更:
type_comments
、mode='func_type'
、feature_version
を追加。
- ast.unparse(ast_obj)
ast.AST オブジェクトを解析解除し、 ast.parse()で解析して戻すと、同等の ast.AST オブジェクトを生成するコードで文字列を生成します。
警告
生成されるコード文字列は、 ast.AST オブジェクトを生成した元のコードと必ずしも同じではありません(定数タプル/フリーズセットなどのコンパイラーの最適化なし)。
警告
非常に複雑な式を解析しようとすると、 RecursionError が発生します。
バージョン3.9の新機能。
- ast.literal_eval(node_or_string)
Pythonリテラルまたはコンテナ表示を含む式ノードまたは文字列を安全に評価します。 提供される文字列またはノードは、次のPythonリテラル構造のみで構成されます:文字列、バイト、数値、タプル、リスト、dict、セット、ブール値、および
None
。これは、信頼できないソースからのPython値を含む文字列を、値を自分で解析することなく安全に評価するために使用できます。 演算子やインデックス付けなど、任意の複雑な式を評価することはできません。
警告
PythonのASTコンパイラではスタックの深さが制限されているため、十分に大きい/複雑な文字列でPythonインタプリタがクラッシュする可能性があります。
バージョン3.2で変更:バイトとセットリテラルを許可するようになりました。
バージョン3.9で変更:
'set()'
を使用した空のセットの作成をサポートするようになりました。
- ast.get_docstring(node, clean=True)
指定されたノード( FunctionDef 、 AsyncFunctionDef 、 ClassDef 、または
Module
ノードである必要があります)のdocstringを返します)、またはdocstringがない場合はNone
。 clean がtrueの場合、 inspect.cleandoc()を使用してdocstringのインデントをクリーンアップします。バージョン3.5で変更: AsyncFunctionDef がサポートされるようになりました。
- ast.get_source_segment(source, node, *, padded=False)
ノードを生成したソースのソースコードセグメントを取得します。 一部の位置情報(
lineno
、end_lineno
、col_offset
、またはend_col_offset
)が欠落している場合は、None
を返します。padded が
True
の場合、複数行のステートメントの最初の行には、元の位置に一致するスペースが埋め込まれます。バージョン3.8の新機能。
- ast.fix_missing_locations(node)
- compile()を使用してノードツリーをコンパイルすると、コンパイラは、それらをサポートするすべてのノードに
lineno
およびcol_offset
属性を期待します。 これは、生成されたノードに入力するのがかなり面倒なので、このヘルパーは、これらの属性を親ノードの値に設定することにより、まだ設定されていない場所に再帰的に追加します。 ノードから再帰的に動作します。
- ast.increment_lineno(node, n=1)
- node から始まるツリー内の各ノードの行番号と終了行番号を n だけインクリメントします。 これは、ファイル内の別の場所に「コードを移動」するのに役立ちます。
- ast.copy_location(new_node, old_node)
- ソースの場所(
lineno
、col_offset
、end_lineno
、およびend_col_offset
)を old_node から new_node にコピーする場合可能で、 new_node を返します。
- ast.iter_fields(node)
- ノードに存在する
node._fields
の各フィールドに対して、(fieldname, value)
のタプルを生成します。
- ast.iter_child_nodes(node)
- node のすべての直接の子ノード、つまり、ノードであるすべてのフィールドと、ノードのリストであるフィールドのすべてのアイテムを生成します。
- ast.walk(node)
- node で始まるツリー内のすべての子孫ノード( node 自体を含む)を指定された順序で再帰的に生成します。 これは、ノードを適切に変更するだけで、コンテキストを気にしない場合に役立ちます。
- class ast.NodeVisitor
抽象構文ツリーをウォークし、見つかったすべてのノードに対してビジター関数を呼び出すノードビジター基本クラス。 この関数は、 visit()メソッドによって転送される値を返す場合があります。
このクラスはサブクラス化されることを意図しており、サブクラスはビジターメソッドを追加します。
- visit(node)
ノードにアクセスします。 デフォルトの実装では、
self.visit_classname
というメソッドが呼び出されます。ここで、 classname はノードクラスの名前であり、そのメソッドが存在しない場合は generic_visit()です。
- generic_visit(node)
この訪問者は、ノードのすべての子で visit()を呼び出します。
カスタムビジターメソッドを持つノードの子ノードは、ビジターが generic_visit()を呼び出すか、それ自体にアクセスしない限り、アクセスされないことに注意してください。
トラバーサル中にノードに変更を適用する場合は、 NodeVisitor を使用しないでください。 このために、変更を許可する特別な訪問者( NodeTransformer )が存在します。
バージョン3.8以降非推奨:メソッド
visit_Num()
、visit_Str()
、visit_Bytes()
、visit_NameConstant()
、visit_Ellipsis()
は非推奨になり、今後のPythonバージョンでは呼び出されません。visit_Constant()
メソッドを追加して、すべての定数ノードを処理します。
- class ast.NodeTransformer
NodeVisitor サブクラスは、抽象構文ツリーをウォークし、ノードの変更を可能にします。
NodeTransformer はASTをウォークし、ビジターメソッドの戻り値を使用して古いノードを置き換えるか削除します。 ビジターメソッドの戻り値が
None
の場合、ノードはその場所から削除されます。それ以外の場合は、戻り値に置き換えられます。 戻り値は元のノードである可能性があり、その場合、置換は行われません。これは、名前ルックアップ(
foo
)のすべてのオカレンスをdata['foo']
に書き換えるトランスフォーマーの例です。class RewriteName(NodeTransformer): def visit_Name(self, node): return Subscript( value=Name(id='data', ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx )
操作しているノードに子ノードがある場合は、子ノードを自分で変換するか、最初にノードの
generic_visit()
メソッドを呼び出す必要があることに注意してください。ステートメントのコレクションの一部であったノード(すべてのステートメントノードに適用される)の場合、訪問者は単一のノードだけでなく、ノードのリストを返すこともあります。
NodeTransformer が場所情報(
lineno
など)を提供せずに新しいノード(元のツリーの一部ではなかった)を導入する場合、 fix_missing_locations()を次のように呼び出す必要があります。位置情報を再計算するための新しいサブツリー:tree = ast.parse('foo', mode='eval') new_tree = fix_missing_locations(RewriteName().visit(tree))
通常、次のようなトランスフォーマーを使用します。
node = YourTransformer().visit(node)
- ast.dump(node, annotate_fields=True, include_attributes=False, *, indent=None)
ノードにあるツリーのフォーマットされたダンプを返します。 これは主にデバッグの目的で役立ちます。 annotate_fields がtrue(デフォルト)の場合、返される文字列にはフィールドの名前と値が表示されます。 annotate_fields がfalseの場合、明確なフィールド名を省略することで、結果の文字列がよりコンパクトになります。 行番号や列オフセットなどの属性は、デフォルトではダンプされません。 これが必要な場合は、 include_attributes をtrueに設定できます。
indent が負でない整数または文字列の場合、ツリーはそのインデントレベルできれいに印刷されます。 インデントレベルが0、負、または
""
の場合、改行のみが挿入されます。None
(デフォルト)は、単一行表現を選択します。 正の整数インデントを使用すると、レベルごとに多くのスペースがインデントされます。 indent が文字列("\t"
など)の場合、その文字列を使用して各レベルがインデントされます。バージョン3.9で変更: インデントオプションが追加されました。
コンパイラフラグ
プログラムのコンパイルへの影響を変更するために、次のフラグを compile()に渡すことができます。
- ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
トップレベルの
await
、async for
、async with
および非同期内包表記のサポートを有効にします。バージョン3.8の新機能。
- ast.PyCF_ONLY_AST
- コンパイルされたコードオブジェクトを返す代わりに、抽象構文ツリーを生成して返します。
- ast.PyCF_TYPE_COMMENTS
PEP 484 および PEP 526 スタイルタイプのコメント(
# type: <type>
、# type: ignore <stuff>
)のサポートを有効にします。バージョン3.8の新機能。
コマンドラインの使用法
バージョン3.9の新機能。
ast モジュールは、コマンドラインからスクリプトとして実行できます。 それは次のように簡単です:
python -m ast [-m <mode>] [-a] [infile]
次のオプションが受け入れられます。
- -h, --help
- ヘルプメッセージを表示して終了します。
- -m <mode>
--mode <mode>
- parse()の mode 引数のように、コンパイルする必要のあるコードの種類を指定します。
- --no-type-comments
- タイプコメントを解析しないでください。
- -a, --include-attributes
- 行番号や列オフセットなどの属性を含めます。
- -i <indent>
--indent <indent>
- AST内のノードのインデント(スペースの数)。
infile
が指定されている場合、その内容はASTに解析され、stdoutにダンプされます。 それ以外の場合、コンテンツはstdinから読み取られます。
も参照してください
Green Tree Snakes 、外部ドキュメントリソースには、PythonASTの操作に関する詳細が記載されています。
ASTTokens は、Python ASTに、それらを生成したソースコード内のトークンとテキストの位置で注釈を付けます。 これは、ソースコードを変換するツールに役立ちます。
leoAst.py は、トークンとastノードの間に双方向リンクを挿入することにより、Pythonプログラムのトークンベースのビューと解析ツリーベースのビューを統合します。
LibCST は、コードをastツリーのように見え、すべてのフォーマットの詳細を保持する具体的な構文ツリーとして解析します。 自動リファクタリング(codemod)アプリケーションやリンターの構築に役立ちます。
Parso は、さまざまなPythonバージョン(複数のPythonバージョン)のエラー回復とラウンドトリップ解析をサポートするPythonパーサーです。 Parsoは、Pythonファイル内の複数の構文エラーを一覧表示することもできます。