ast --- Abstract syntax trees¶
ソースコード: Lib/ast.py
ast モジュールは、Python アプリケーションで Python の抽象構文木を処理しやすくするものです。抽象構文そのものは、Python のリリースごとに変化する可能性があります。このモジュールを使用すると、現在の文法をプログラム上で知る助けになるでしょう。
抽象構文木を作成するには、 ast.PyCF_ONLY_AST を組み込み関数 compile() のフラグとして渡すか、あるいはこのモジュールで提供されているヘルパー関数 parse() を使います。その結果は、 ast.AST を継承したクラスのオブジェクトのツリーとなります。抽象構文木は組み込み関数 compile() を使って Python コード・オブジェクトにコンパイルすることができます。
Abstract grammar¶
抽象文法は、現在次のように定義されています:
-- 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, type_param* type_params)
          | AsyncFunctionDef(identifier name, arguments args,
                             stmt* body, expr* decorator_list, expr? returns,
                             string? type_comment, type_param* type_params)
          | ClassDef(identifier name,
             expr* bases,
             keyword* keywords,
             stmt* body,
             expr* decorator_list,
             type_param* type_params)
          | Return(expr? value)
          | Delete(expr* targets)
          | Assign(expr* targets, expr value, string? type_comment)
          | TypeAlias(expr name, type_param* type_params, expr value)
          | 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)
          | Match(expr subject, match_case* cases)
          | Raise(expr? exc, expr? cause)
          | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
          | TryStar(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)
         | Interpolation(expr value, constant str, int conversion, expr? format_spec)
         | JoinedStr(expr* values)
         | TemplateStr(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)
             attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
    withitem = (expr context_expr, expr? optional_vars)
    match_case = (pattern pattern, expr? guard, stmt* body)
    pattern = MatchValue(expr value)
            | MatchSingleton(constant value)
            | MatchSequence(pattern* patterns)
            | MatchMapping(expr* keys, pattern* patterns, identifier? rest)
            | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)
            | MatchStar(identifier? name)
            -- The optional "rest" MatchMapping parameter handles capturing extra mapping keys
            | MatchAs(pattern? pattern, identifier? name)
            | MatchOr(pattern* patterns)
             attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
    type_ignore = TypeIgnore(int lineno, string tag)
    type_param = TypeVar(identifier name, expr? bound, expr? default_value)
               | ParamSpec(identifier name, expr? default_value)
               | TypeVarTuple(identifier name, expr? default_value)
               attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
}
Node クラス¶
- class ast.AST¶
- このクラスは全ての AST ノード・クラスの基底です。実際のノード・クラスは 先に 示した - Parser/Python.asdlファイルから派生したものです。これらのクラスは- _astC モジュールで定義され、- astにもエクスポートし直されています。- 抽象文法の左辺のシンボル一つずつにそれぞれ一つのクラスがあります (たとえば - ast.stmtや- ast.expr)。それに加えて、右辺のコンストラクタ一つずつにそれぞれ一つのクラスがあり、これらのクラスは左辺のツリーのクラスを継承しています。たとえば、- ast.BinOpは- ast.exprから継承しています。代替を伴った生成規則 (production rules with alternatives) (別名 "sums") の場合、左辺は抽象クラスとなり、特定のコンストラクタ・ノードのインスタンスのみが作成されます。- _fields¶
- 各具象クラスは属性 - _fieldsを持っており、すべての子ノードの名前をそこに保持しています。- 具象クラスのインスタンスは、各子ノードに対してそれぞれひとつの属性を持っています。この属性は、文法で定義された型となります。たとえば - ast.BinOpのインスタンスは- leftという属性を持っており、その型は- ast.exprです。- これらの属性が、文法上 (クエスチョンマークを用いて) オプションであるとマークされている場合は、その値が - Noneとなることもあります。属性が0個以上の複数の値をとりうる場合 (アスタリスクでマークされている場合) は、値は Python のリストで表されます。全ての属性は AST を- compile()でコンパイルする際には存在しなければならず、そして妥当な値でなければなりません。
 - _field_types¶
- The - _field_typesattribute on each concrete class is a dictionary mapping field names (as also listed in- _fields) to their types.- >>> ast.TypeVar._field_types {'name': <class 'str'>, 'bound': ast.expr | None, 'default_value': ast.expr | None} - Added in version 3.13. 
 - 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 オフセットはパーサが内部で使用するので記録されます。- コンパイラは終了位置を必要としないことに注意してください。このため終了位置は省略可能です。終了位置を示すオフセットは最後のシンボルの 後の位置 になります。例えば一行で書かれた式のソースコードのセグメントは - source_line[node.col_offset : node.end_col_offset]により取得できます。
 - クラス - ast.Tのコンストラクタは引数を次のように解析します:- 位置引数があるとすれば、 - T._fieldsにあるのと同じだけの個数が無ければなりません。これらの引数はそこにある名前を持った属性として割り当てられます。
- キーワード引数があるとすれば、それらはその名前の属性にその値を割り当てられます。 
 - たとえば、 - ast.UnaryOpノードを生成して属性を埋めるには、次のようにすることができます- node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0), lineno=0, col_offset=0) - If a field that is optional in the grammar is omitted from the constructor, it defaults to - None. If a list field is omitted, it defaults to the empty list. If a field of type- ast.expr_contextis omitted, it defaults to- Load(). If any other field is omitted, a- DeprecationWarningis raised and the AST node will not have this field. In Python 3.15, this condition will raise an error.
バージョン 3.8 で変更: ast.Constant が全ての定数に使われるようになりました。
バージョン 3.9 で変更: 単純なインデックスはその値で表現され、幅を持つスライスはタプルで表現されます。
バージョン 3.14 で変更: The __repr__() output of AST nodes includes
the values of the node fields.
バージョン 3.8 で非推奨: Old classes ast.Num, ast.Str, ast.Bytes,
ast.NameConstant and ast.Ellipsis are still available,
but they will be removed in future Python releases.  In the meantime,
instantiating them will return an instance of a different class.
バージョン 3.9 で非推奨: Old classes ast.Index and ast.ExtSlice are still
available, but they will be removed in future Python releases.
In the meantime, instantiating them will return an instance of
a different class.
Deprecated since version 3.13, removed in version 3.15: Previous versions of Python allowed the creation of AST nodes that were missing required fields. Similarly, AST node constructors allowed arbitrary keyword arguments that were set as attributes of the AST node, even if they did not match any of the fields of the AST node. This behavior is deprecated and will be removed in Python 3.15.
注釈
ここに示されている特定のノードクラスについての記述は、素晴らしい Green Tree Snakes プロジェクトとそのすべての貢献者の成果物をもとにしています。
Root nodes¶
- class ast.Module(body, type_ignores)¶
- A Python module, as with file input. Node type generated by - ast.parse()in the default- "exec"mode.- bodyis a- listof the module's 文 (Statements).- type_ignoresis a- listof the module's type ignore comments; see- ast.parse()for more details.- >>> print(ast.dump(ast.parse('x = 1'), indent=4)) Module( body=[ Assign( targets=[ Name(id='x', ctx=Store())], value=Constant(value=1))]) 
- class ast.Expression(body)¶
- A single Python expression input. Node type generated by - ast.parse()when mode is- "eval".- bodyis a single node, one of the expression types.- >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) Expression( body=Constant(value=123)) 
- class ast.Interactive(body)¶
- A single interactive input, like in 対話モード. Node type generated by - ast.parse()when mode is- "single".- bodyis a- listof statement nodes.- >>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4)) Interactive( body=[ Assign( targets=[ Name(id='x', ctx=Store())], value=Constant(value=1)), Assign( targets=[ Name(id='y', ctx=Store())], value=Constant(value=2))]) 
- class ast.FunctionType(argtypes, returns)¶
- A representation of an old-style type comments for functions, as Python versions prior to 3.5 didn't support PEP 484 annotations. Node type generated by - ast.parse()when mode is- "func_type".- Such type comments would look like this: - def sum_two_number(a, b): # type: (int, int) -> int return a + b - argtypesis a- listof expression nodes.- returnsis a single expression node.- >>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4)) FunctionType( argtypes=[ Name(id='int'), Name(id='str')], returns=Subscript( value=Name(id='List'), slice=Name(id='int'))) - Added in version 3.8. 
リテラル¶
- class ast.Constant(value)¶
- A constant value. The - valueattribute of the- Constantliteral contains the Python object it represents. The values represented can be instances of- str,- bytes,- int,- float,- complex, and- bool, and the constants- Noneand- Ellipsis.- >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4)) Expression( body=Constant(value=123)) 
- class ast.FormattedValue(value, conversion, format_spec)¶
- このノードは f-string における単一の書式指定置換フィールドを表現します。文字列が単一の置換フィールドしか持たず、他に何も含まない場合は、ノードは単独で存在できます。そうでない場合は - JoinedStrの一部としてあらわれます。
- class ast.JoinedStr(values)¶
- FormattedValueノードと- Constantノードの集まりからなる f-string です。- >>> 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'), conversion=-1), Constant(value=') is '), FormattedValue( value=Call( func=Name(id='sin'), args=[ Name(id='a')]), conversion=-1, format_spec=JoinedStr( values=[ Constant(value='.3')]))])) 
- class ast.TemplateStr(values, /)¶
- Added in version 3.14. - Node representing a template string literal, comprising a series of - Interpolationand- Constantnodes. These nodes may be any order, and do not need to be interleaved.- >>> expr = ast.parse('t"{name} finished {place:ordinal}"', mode='eval') >>> print(ast.dump(expr, indent=4)) Expression( body=TemplateStr( values=[ Interpolation( value=Name(id='name'), str='name', conversion=-1), Constant(value=' finished '), Interpolation( value=Name(id='place'), str='place', conversion=-1, format_spec=JoinedStr( values=[ Constant(value='ordinal')]))])) 
- class ast.Interpolation(value, str, conversion, format_spec=None)¶
- Added in version 3.14. - Node representing a single interpolation field in a template string literal. - valueis any expression node (such as a literal, a variable, or a function call). This has the same meaning as- FormattedValue.value.
- stris a constant containing the text of the interpolation expression.- If - stris set to- None, then- valueis used to generate code when calling- ast.unparse(). This no longer guarantees that the generated code is identical to the original and is intended for code generation.
- conversionは整数です:- -1: no conversion 
- 97 ( - ord('a')):- !a- ASCIIconversion
- 114 ( - ord('r')):- !r- repr()conversion
- 115 ( - ord('s')):- !s- stringconversion
 - This has the same meaning as - FormattedValue.conversion.
- format_specis a- JoinedStrnode representing the formatting of the value, or- Noneif no format was specified. Both- conversionand- format_speccan be set at the same time. This has the same meaning as- FormattedValue.format_spec.
 
- class ast.List(elts, ctx)¶
- class ast.Tuple(elts, ctx)¶
- リストまたはタプルをあらわします。 - eltsは内包する要素を表現するノードのリストを保持します。- ctxはコンテナが代入のターゲットである場合 (たとえば- (x,y)=somethingのような場合) は- Storeであり、そうでない場合は- 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)])) >>> 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)])) 
- class ast.Set(elts)¶
- 集合 (set) をあらわします。 - 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リストに入り、- keysの対応する位置には- Noneが入ります。- >>> 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')])) 
変数¶
- class ast.Name(id, ctx)¶
- 変数名をあらわします。 - idは変数名を文字列で保持し、- ctxは以下に示す型のいずれかです。
- class ast.Load¶
- class ast.Store¶
- class ast.Del¶
- 変数の参照は変数の値をロードするか、新しい値を割り当てるか、または値を削除するために使うことができます。変数の参照はこれら3つの場合を区別するためのコンテキストによって与えられます。 - >>> print(ast.dump(ast.parse('a'), indent=4)) Module( body=[ Expr( value=Name(id='a'))]) >>> print(ast.dump(ast.parse('a = 1'), indent=4)) Module( body=[ Assign( targets=[ Name(id='a', ctx=Store())], value=Constant(value=1))]) >>> print(ast.dump(ast.parse('del a'), indent=4)) Module( body=[ Delete( targets=[ Name(id='a', ctx=Del())])]) 
- 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'))]) 
式 (expression)¶
- class ast.Expr(value)¶
- 関数呼び出しのような式がそれ自身で文となり、戻り値が使われないかまたは保存されないとき、その式はこのコンテナでラップされます。 - valueはこの節で説明する他のノード、- Constantノード、- Nameノード、- Lambdaノード- Yieldノードまたは- YieldFromノードのいずれかを保持します。- >>> print(ast.dump(ast.parse('-a'), indent=4)) Module( body=[ Expr( value=UnaryOp( op=USub(), operand=Name(id='a')))]) 
- 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'))) 
- 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'), op=Add(), right=Name(id='y'))) 
- 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)¶
- 'or' や 'and' のような論理演算をあらわします。 - opは- Orまたは- Andです。- valuesは必要な値のリストです。- a or b or cのように同じ演算子を使う連続した演算は、複数の値を持った単一のノードとして表現されます。- notは単項演算- UnaryOpのため、ここには含まれません。- >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4)) Expression( body=BoolOp( op=Or(), values=[ Name(id='x'), Name(id='y')])) 
- class ast.Compare(left, ops, comparators)¶
- 2つ以上の値の比較をあらわします。 - left比較の中の最初の値、- opsは演算子のリスト、- comparatorsは2つ目以降の値のリストです。- >>> 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'), 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)¶
- 関数呼び出しをあらわします。 - funcは関数で、多くの場合- Nameまたは- Attributeのオブジェクトです。 関数呼び出しの引数:- argsは位置引数のリストを保持します。
- keywordsholds a list of- keywordobjects representing arguments passed by keyword.
 - The - argsand- keywordsarguments are optional and default to empty lists.- >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4)) Expression( body=Call( func=Name(id='func'), args=[ Name(id='a'), Starred( value=Name(id='d'))], keywords=[ keyword( arg='b', value=Name(id='c')), keyword( value=Name(id='e'))])) 
- 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'), body=Name(id='a'), orelse=Name(id='c'))) 
- 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'), attr='colour')) 
- 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))) - Added in version 3.8. 
配列要素の参照 (Subscripting)¶
- class ast.Subscript(value, slice, ctx)¶
- l[1]のような配列要素の参照をあらわします。- valueは参照元のオブジェクトです (通常シーケンス型またはマッピング型)。- sliceはインデックス、スライス、またはキーです。- Sliceを含む- Tupleでもかまいません。- ctxは要素の参照により実行されるアクションに応じて- Load、- Storeまたは- Delのいずれかです。- >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4)) Expression( body=Subscript( value=Name(id='l'), slice=Tuple( elts=[ Slice( lower=Constant(value=1), upper=Constant(value=2)), Constant(value=3)]))) 
- 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'), slice=Slice( lower=Constant(value=1), upper=Constant(value=2)))) 
内包表記 (Comprehension)¶
- 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は- comprehensionノードのリストです。- >>> print(ast.dump( ... ast.parse('[x for x in numbers]', mode='eval'), ... indent=4, ... )) Expression( body=ListComp( elt=Name(id='x'), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers'), 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'), value=BinOp( left=Name(id='x'), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers'), is_async=0)])) >>> print(ast.dump( ... ast.parse('{x for x in numbers}', mode='eval'), ... indent=4, ... )) Expression( body=SetComp( elt=Name(id='x'), generators=[ comprehension( target=Name(id='x', ctx=Store()), iter=Name(id='numbers'), is_async=0)])) 
- class ast.comprehension(target, iter, ifs, is_async)¶
- 内包表記におけるひとつの - for節をあらわします。- targetは各要素への参照です - 典型的には- Nameまたは- Tupleノードです。- iterはイテレートする対象のオブジェクトです。- ifsは条件節のリストです: 各- for節は複数の- ifsを持つことができます。- is_asyncは内包表記が非同期であることを示します (- async forを- 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'), args=[ Name(id='c')]), generators=[ comprehension( target=Name(id='line', ctx=Store()), iter=Name(id='file'), is_async=0), comprehension( target=Name(id='c', ctx=Store()), iter=Name(id='line'), 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'), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='n', ctx=Store()), iter=Name(id='it'), ifs=[ Compare( left=Name(id='n'), ops=[ Gt()], comparators=[ Constant(value=5)]), Compare( left=Name(id='n'), 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'), generators=[ comprehension( target=Name(id='i', ctx=Store()), iter=Name(id='soc'), is_async=1)])) 
文 (Statements)¶
- class ast.Assign(targets, value, type_comment)¶
- 代入です。 - targetsはノードのリスト、- valueは単一のノードです。- targetsの複数のノードは、それぞれに対して同じ値を代入することをあらわします。分割代入は- targets内に- Tupleまたは- Listを置くことで表現されます。- 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))]) >>> 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'))]) 
- class ast.AnnAssign(target, annotation, value, simple)¶
- An assignment with a type annotation. - targetis a single node and can be a- Name, an- Attributeor a- Subscript.- annotationis the annotation, such as a- Constantor- Namenode.- valueis a single optional node.- simpleis always either 0 (indicating a "complex" target) or 1 (indicating a "simple" target). A "simple" target consists solely of a- Namenode that does not appear between parentheses; all other targets are considered complex. Only simple targets appear in the- __annotations__dictionary of modules and classes.- >>> print(ast.dump(ast.parse('c: int'), indent=4)) Module( body=[ AnnAssign( target=Name(id='c', ctx=Store()), annotation=Name(id='int'), simple=1)]) >>> 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'), value=Constant(value=1), simple=0)]) >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation Module( body=[ AnnAssign( target=Attribute( value=Name(id='a'), attr='b', ctx=Store()), annotation=Name(id='int'), simple=0)]) >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation Module( body=[ AnnAssign( target=Subscript( value=Name(id='a'), slice=Constant(value=1), ctx=Store()), annotation=Name(id='int'), simple=0)]) 
- class ast.AugAssign(target, op, value)¶
- a += 1のような累積代入をあらわします。下記の例では、- targetは (- Storeコンテキストを伴う)- xのための- Nameノード、- opは- Add演算子、そして- valueは定数1をあらわす- Constantノードです。- Assignと異なり、- target属性は class- 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))]) 
- 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'), cause=Name(id='y'))]) 
- 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'), msg=Name(id='y'))]) 
- 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())])]) 
- class ast.Pass¶
- pass文をあらわします。- >>> print(ast.dump(ast.parse('pass'), indent=4)) Module( body=[ Pass()]) 
- class ast.TypeAlias(name, type_params, value)¶
- A type alias created through the - typestatement.- nameis the name of the alias,- type_paramsis a list of type parameters, and- valueis the value of the type alias.- >>> print(ast.dump(ast.parse('type Alias = int'), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), value=Name(id='int'))]) - Added in version 3.12. 
関数またはループの内部でのみ適用可能な他の文は、別のセクションで説明します。
インポート¶
- class ast.Import(names)¶
- インポート文です。 - namesは- aliasノードのリストです。- >>> print(ast.dump(ast.parse('import x,y,z'), indent=4)) Module( body=[ Import( names=[ alias(name='x'), alias(name='y'), alias(name='z')])]) 
- 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)]) 
- 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)]) 
制御フロー¶
注釈
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'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ If( test=Name(id='y'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])])]) 
- class ast.For(target, iter, body, orelse, type_comment)¶
- A - forloop.- targetholds the variable(s) the loop assigns to, as a single- Name,- Tuple,- List,- Attributeor- Subscriptnode.- iterholds the item to be looped over, again as a single node.- bodyand- orelsecontain lists of nodes to execute. Those in- orelseare executed if the loop finishes normally, rather than via a- breakstatement.- 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'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])]) 
- 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'), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])]) 
- 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'), body=[ If( test=Compare( left=Name(id='a'), ops=[ Gt()], comparators=[ Constant(value=5)]), body=[ Break()], orelse=[ Continue()])])]) 
- 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'), body=[ Expr( value=Constant(value=Ellipsis))]), ExceptHandler( type=Name(id='OtherException'), name='e', body=[ Expr( value=Constant(value=Ellipsis))])], orelse=[ Expr( value=Constant(value=Ellipsis))], finalbody=[ Expr( value=Constant(value=Ellipsis))])]) 
- class ast.TryStar(body, handlers, orelse, finalbody)¶
- tryblocks which are followed by- except*clauses. The attributes are the same as for- Trybut the- ExceptHandlernodes in- handlersare interpreted as- except*blocks rather then- except.- >>> print(ast.dump(ast.parse(""" ... try: ... ... ... except* Exception: ... ... ... """), indent=4)) Module( body=[ TryStar( body=[ Expr( value=Constant(value=Ellipsis))], handlers=[ ExceptHandler( type=Name(id='Exception'), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.11. 
- class ast.ExceptHandler(type, name, body)¶
- 単一の - except節をあらわします。- typeはこの節にマッチする例外のタイプで、典型的には- Nameノードです (- Noneを指定すると全ての例外をキャッチする- except:節をあらわします)。- 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'), op=Add(), right=Constant(value=1)))], handlers=[ ExceptHandler( type=Name(id='TypeError'), body=[ Pass()])])]) 
- 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に相当する- Name,- Tupleまたは- Listのいずれかのノードか、または、この部分が不要な場合は- 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'), optional_vars=Name(id='b', ctx=Store())), withitem( context_expr=Name(id='c'), optional_vars=Name(id='d', ctx=Store()))], body=[ Expr( value=Call( func=Name(id='something'), args=[ Name(id='b'), Name(id='d')]))])]) 
Pattern matching¶
- class ast.Match(subject, cases)¶
- A - matchstatement.- subjectholds the subject of the match (the object that is being matched against the cases) and- casescontains an iterable of- match_casenodes with the different cases.- Added in version 3.10. 
- class ast.match_case(pattern, guard, body)¶
- A single case pattern in a - matchstatement.- patterncontains the match pattern that the subject will be matched against. Note that the- ASTnodes produced for patterns differ from those produced for expressions, even when they share the same syntax.- The - guardattribute contains an expression that will be evaluated if the pattern matches the subject.- bodycontains a list of nodes to execute if the pattern matches and the result of evaluating the guard expression is true.- >>> print(ast.dump(ast.parse(""" ... match x: ... case [x] if x>0: ... ... ... case tuple(): ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchAs(name='x')]), guard=Compare( left=Name(id='x'), ops=[ Gt()], comparators=[ Constant(value=0)]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchClass( cls=Name(id='tuple')), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchValue(value)¶
- A match literal or value pattern that compares by equality. - valueis an expression node. Permitted value nodes are restricted as described in the match statement documentation. This pattern succeeds if the match subject is equal to the evaluated value.- >>> print(ast.dump(ast.parse(""" ... match x: ... case "Relevant": ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchValue( value=Constant(value='Relevant')), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchSingleton(value)¶
- A match literal pattern that compares by identity. - valueis the singleton to be compared against:- None,- True, or- False. This pattern succeeds if the match subject is the given constant.- >>> print(ast.dump(ast.parse(""" ... match x: ... case None: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSingleton(value=None), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchSequence(patterns)¶
- A match sequence pattern. - patternscontains the patterns to be matched against the subject elements if the subject is a sequence. Matches a variable length sequence if one of the subpatterns is a- MatchStarnode, otherwise matches a fixed length sequence.- >>> print(ast.dump(ast.parse(""" ... match x: ... case [1, 2]: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchValue( value=Constant(value=1)), MatchValue( value=Constant(value=2))]), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchStar(name)¶
- Matches the rest of the sequence in a variable length match sequence pattern. If - nameis not- None, a list containing the remaining sequence elements is bound to that name if the overall sequence pattern is successful.- >>> print(ast.dump(ast.parse(""" ... match x: ... case [1, 2, *rest]: ... ... ... case [*_]: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchValue( value=Constant(value=1)), MatchValue( value=Constant(value=2)), MatchStar(name='rest')]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchSequence( patterns=[ MatchStar()]), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchMapping(keys, patterns, rest)¶
- A match mapping pattern. - keysis a sequence of expression nodes.- patternsis a corresponding sequence of pattern nodes.- restis an optional name that can be specified to capture the remaining mapping elements. Permitted key expressions are restricted as described in the match statement documentation.- This pattern succeeds if the subject is a mapping, all evaluated key expressions are present in the mapping, and the value corresponding to each key matches the corresponding subpattern. If - restis not- None, a dict containing the remaining mapping elements is bound to that name if the overall mapping pattern is successful.- >>> print(ast.dump(ast.parse(""" ... match x: ... case {1: _, 2: _}: ... ... ... case {**rest}: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchMapping( keys=[ Constant(value=1), Constant(value=2)], patterns=[ MatchAs(), MatchAs()]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchMapping(rest='rest'), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchClass(cls, patterns, kwd_attrs, kwd_patterns)¶
- A match class pattern. - clsis an expression giving the nominal class to be matched.- patternsis a sequence of pattern nodes to be matched against the class defined sequence of pattern matching attributes.- kwd_attrsis a sequence of additional attributes to be matched (specified as keyword arguments in the class pattern),- kwd_patternsare the corresponding patterns (specified as keyword values in the class pattern).- This pattern succeeds if the subject is an instance of the nominated class, all positional patterns match the corresponding class-defined attributes, and any specified keyword attributes match their corresponding pattern. - Note: classes may define a property that returns self in order to match a pattern node against the instance being matched. Several builtin types are also matched that way, as described in the match statement documentation. - >>> print(ast.dump(ast.parse(""" ... match x: ... case Point2D(0, 0): ... ... ... case Point3D(x=0, y=0, z=0): ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchClass( cls=Name(id='Point2D'), patterns=[ MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0))]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchClass( cls=Name(id='Point3D'), kwd_attrs=[ 'x', 'y', 'z'], kwd_patterns=[ MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0))]), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchAs(pattern, name)¶
- A match "as-pattern", capture pattern or wildcard pattern. - patterncontains the match pattern that the subject will be matched against. If the pattern is- None, the node represents a capture pattern (i.e a bare name) and will always succeed.- The - nameattribute contains the name that will be bound if the pattern is successful. If- nameis- None,- patternmust also be- Noneand the node represents the wildcard pattern.- >>> print(ast.dump(ast.parse(""" ... match x: ... case [x] as y: ... ... ... case _: ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchAs( pattern=MatchSequence( patterns=[ MatchAs(name='x')]), name='y'), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchAs(), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
- class ast.MatchOr(patterns)¶
- A match "or-pattern". An or-pattern matches each of its subpatterns in turn to the subject, until one succeeds. The or-pattern is then deemed to succeed. If none of the subpatterns succeed the or-pattern fails. The - patternsattribute contains a list of match pattern nodes that will be matched against the subject.- >>> print(ast.dump(ast.parse(""" ... match x: ... case [x] | (y): ... ... ... """), indent=4)) Module( body=[ Match( subject=Name(id='x'), cases=[ match_case( pattern=MatchOr( patterns=[ MatchSequence( patterns=[ MatchAs(name='x')]), MatchAs(name='y')]), body=[ Expr( value=Constant(value=Ellipsis))])])]) - Added in version 3.10. 
Type annotations¶
- class ast.TypeIgnore(lineno, tag)¶
- A - # type: ignorecomment located at lineno. tag is the optional tag specified by the form- # type: ignore <tag>.- >>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), indent=4)) Module( body=[ Assign( targets=[ Name(id='x', ctx=Store())], value=Constant(value=1))], type_ignores=[ TypeIgnore(lineno=1, tag='')]) >>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', type_comments=True), indent=4)) Module( body=[ AnnAssign( target=Name(id='x', ctx=Store()), annotation=Name(id='bool'), value=Constant(value=1), simple=1)], type_ignores=[ TypeIgnore(lineno=1, tag='[assignment]')]) - 注釈 - TypeIgnorenodes are not generated when the type_comments parameter is set to- False(default). See- ast.parse()for more details.- Added in version 3.8. 
Type parameters¶
Type parameters can exist on classes, functions, and type aliases.
- class ast.TypeVar(name, bound, default_value)¶
- A - typing.TypeVar.- nameis the name of the type variable.- boundis the bound or constraints, if any. If- boundis a- Tuple, it represents constraints; otherwise it represents the bound.- default_valueis the default value; if the- TypeVarhas no default, this attribute will be set to- None.- >>> print(ast.dump(ast.parse("type Alias[T: int = bool] = list[T]"), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), type_params=[ TypeVar( name='T', bound=Name(id='int'), default_value=Name(id='bool'))], value=Subscript( value=Name(id='list'), slice=Name(id='T')))]) - Added in version 3.12. - バージョン 3.13 で変更: Added the default_value parameter. 
- class ast.ParamSpec(name, default_value)¶
- A - typing.ParamSpec.- nameis the name of the parameter specification.- default_valueis the default value; if the- ParamSpechas no default, this attribute will be set to- None.- >>> print(ast.dump(ast.parse("type Alias[**P = [int, str]] = Callable[P, int]"), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), type_params=[ ParamSpec( name='P', default_value=List( elts=[ Name(id='int'), Name(id='str')]))], value=Subscript( value=Name(id='Callable'), slice=Tuple( elts=[ Name(id='P'), Name(id='int')])))]) - Added in version 3.12. - バージョン 3.13 で変更: Added the default_value parameter. 
- class ast.TypeVarTuple(name, default_value)¶
- A - typing.TypeVarTuple.- nameis the name of the type variable tuple.- default_valueis the default value; if the- TypeVarTuplehas no default, this attribute will be set to- None.- >>> print(ast.dump(ast.parse("type Alias[*Ts = ()] = tuple[*Ts]"), indent=4)) Module( body=[ TypeAlias( name=Name(id='Alias', ctx=Store()), type_params=[ TypeVarTuple(name='Ts', default_value=Tuple())], value=Subscript( value=Name(id='tuple'), slice=Tuple( elts=[ Starred( value=Name(id='Ts'))])))]) - Added in version 3.12. - バージョン 3.13 で変更: Added the default_value parameter. 
関数およびクラス定義¶
- class ast.FunctionDef(name, args, body, decorator_list, returns, type_comment, type_params)¶
- 関数定義です。 - nameは関数名をあらわす生の文字列です。
- argsは引数をあらわす- argumentsノードです。
- bodyは関数の本体をあらわすノードのリストです。
- decorator_listは関数に適用されるデコレータのリストで、外側のデコレータがリストの先頭に保存されます (すなわち、リストの先頭にあるデコレータが最後に適用されます)。
- returnsは戻り値に対する注釈です。
- type_paramsis a list of type parameters.
 - type_comment¶
- type_commentはコメントとして型アノテーションをあらわすオプション文字列です。
 - バージョン 3.12 で変更: Added - type_params.
- 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( args=[ arg(arg='x'), arg(arg='y')]), body=Constant(value=Ellipsis)))]) 
- class ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)¶
- 関数の引数 
- class ast.arg(arg, annotation, type_comment)¶
- A single argument in a list. - argis a raw string of the argument name;- annotationis its annotation, such as a- Namenode.- 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( 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'), Name(id='decorator2')], returns=Constant(value='return annotation'))]) 
- class ast.Return(value)¶
- return文です。- >>> print(ast.dump(ast.parse('return 4'), indent=4)) Module( body=[ Return( value=Constant(value=4))]) 
- class ast.Yield(value)¶
- class ast.YieldFrom(value)¶
- A - yieldor- yield fromexpression. Because these are expressions, they must be wrapped in an- Exprnode if the value sent back is not used.- >>> print(ast.dump(ast.parse('yield x'), indent=4)) Module( body=[ Expr( value=Yield( value=Name(id='x')))]) >>> print(ast.dump(ast.parse('yield from x'), indent=4)) Module( body=[ Expr( value=YieldFrom( value=Name(id='x')))]) 
- 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'])]) >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4)) Module( body=[ Nonlocal( names=[ 'x', 'y', 'z'])]) 
- class ast.ClassDef(name, bases, keywords, body, decorator_list, type_params)¶
- クラス定義です。 - nameはクラス名をあらわす生の文字列です。
- basesは明示的に指定された基底クラスをあらわすノードのリストです。
- keywordsis a list of- keywordnodes, principally for 'metaclass'. Other keywords will be passed to the metaclass, as per PEP 3115.
- bodyはクラス定義に含まれるコードをあらわすノードのリストです。
- decorator_listはノードのリストで、関数定義- FunctionDefの場合と同様に解釈されます。
- type_paramsis a list of type parameters.
 - >>> 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'), Name(id='base2')], keywords=[ keyword( arg='metaclass', value=Name(id='meta'))], body=[ Pass()], decorator_list=[ Name(id='decorator1'), Name(id='decorator2')])]) - バージョン 3.12 で変更: Added - type_params.
async と await¶
- class ast.AsyncFunctionDef(name, args, body, decorator_list, returns, type_comment, type_params)¶
- async def形式の関数定義です。通常の関数定義- FunctionDefと同じフィールドを持ちます。- バージョン 3.12 で変更: Added - type_params.
- class ast.Await(value)¶
- await式をあらわします。- valueは待ち受ける値です。- AsyncFunctionDefの本体 (body) の中でのみ有効です。
>>> print(ast.dump(ast.parse("""\
... async def f():
...     await other_func()
... """), indent=4))
Module(
    body=[
        AsyncFunctionDef(
            name='f',
            args=arguments(),
            body=[
                Expr(
                    value=Await(
                        value=Call(
                            func=Name(id='other_func'))))])])
- class ast.AsyncFor(target, iter, body, orelse, type_comment)¶
- class ast.AsyncWith(items, body, type_comment)¶
- async forループと- async withコンテキストマネージャです。それぞれ- Forおよび- Withと同じフィールドを持ちます。- AsyncFunctionDefの本体 (body) の中でのみ有効です。
注釈
When a string is parsed by ast.parse(), operator nodes (subclasses
of ast.operator, ast.unaryop, ast.cmpop,
ast.boolop and ast.expr_context) on the returned tree
will be singletons. Changes to one will be reflected in all other
occurrences of the same value (for example, ast.Add).
ast helpers¶
ノード・クラスの他に、 ast モジュールは以下のような抽象構文木をトラバースするためのユーティリティ関数やクラスも定義しています:
- ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1)¶
- Parse the source into an AST node. Equivalent to - compile(source, filename, mode, flags=FLAGS_VALUE, optimize=optimize), where- FLAGS_VALUEis- ast.PyCF_ONLY_ASTif- optimize <= 0and- ast.PyCF_OPTIMIZED_ASTotherwise.- If - type_comments=Trueis given, the parser is modified to check and return type comments as specified by PEP 484 and PEP 526. This is equivalent to adding- ast.PyCF_TYPE_COMMENTSto the flags passed to- compile(). This will report syntax errors for misplaced type comments. Without this flag, type comments will be ignored, and the- type_commentfield on selected AST nodes will always be- None. In addition, the locations of- # type: ignorecomments will be returned as the- type_ignoresattribute of- Module(otherwise it is always an empty list).- さらに - modeが- 'func_type'の場合、入力構文は、たとえば- (str, int) -> List[str]のような PEP 484 の "シグネチャ型コメント (signature type comments)" に対応するように修正されます。- Setting - feature_versionto a tuple- (major, minor)will result in a "best-effort" attempt to parse using that Python version's grammar. For example, setting- feature_version=(3, 9)will attempt to disallow parsing of- matchstatements. Currently- majormust equal to- 3. The lowest supported version is- (3, 7)(and this may increase in future Python versions); the highest is- sys.version_info[0:2]. "Best-effort" attempt means there is no guarantee that the parse (or success of the parse) is the same as when run on the Python version corresponding to- feature_version.- If source contains a null character ( - \0),- ValueErroris raised.- 警告 - Note that successfully parsing source code into an AST object doesn't guarantee that the source code provided is valid Python code that can be executed as the compilation step can raise further - SyntaxErrorexceptions. For instance, the source- return 42generates a valid AST node for a return statement, but it cannot be compiled alone (it needs to be inside a function node).- In particular, - ast.parse()won't do any scoping checks, which the compilation step does.- 警告 - 十分に大きい文字列や複雑な文字列によって Python の抽象構文木コンパイラのスタックの深さの限界を越えることで、 Python インタプリタをクラッシュさせることができます。 - バージョン 3.8 で変更: - type_comments、- mode='func_type'、- feature_versionが追加されました。- バージョン 3.13 で変更: The minimum supported version for - feature_versionis now- (3, 7). The- optimizeargument was added.
- ast.unparse(ast_obj)¶
- ast.ASTオブジェクトを逆に構文解析して、- ast.parse()が元の- ast.ASTと等価なオブジェクトを生成できるような文字列を生成します。- 警告 - 生成されたコード文字列は、生成元のコードである - ast.ASTオブジェクトと必ずしも等価であるとは限りません (定数タプルや frozenset などに対するコンパイラ最適化なしのコードです)。- 警告 - 非常に複雑な式を逆構文解析すると - RecursionErrorとなることがあります。- Added in version 3.9. 
- ast.literal_eval(node_or_string)¶
- Python のリテラルやコンテナ表現のみを含む式ノードまたは文字列を評価します。与えられる文字列またはノードは次の Python リテラル構造のみからなるものに限られます: 文字列、バイト列、数、タプル、リスト、辞書、集合、ブール値、 - None、- Ellipsis。- この関数は Python の式を含んだ文字列を、値自身を解析することなしに評価するのに使えます。この関数は、例えば演算や添え字を含んだ任意の複雑な表現を評価するのには使えません。 - This function had been documented as "safe" in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general - eval(). There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.- 警告 - Python の抽象構文木コンパイラのスタックの深さの限界を越えることで、 Python インタプリタをクラッシュさせる可能性があります。 - It can raise - ValueError,- TypeError,- SyntaxError,- MemoryErrorand- RecursionErrordepending on the malformed input.- バージョン 3.2 で変更: バイト列リテラルと集合リテラルが受け取れるようになりました。 - バージョン 3.9 で変更: - 'set()'による空の集合の生成をサポートするようになりました。- バージョン 3.10 で変更: For string inputs, leading spaces and tabs are now stripped. 
- ast.get_docstring(node, clean=True)¶
- 与えられた node (これは - FunctionDef,- AsyncFunctionDef,- ClassDef,- Moduleのいずれかのノードでなければなりません) のドキュメント文字列を返します。もしドキュメント文字列が無ければ- Noneを返します。 clean が真ならば、ドキュメント文字列のインデントを- inspect.cleandoc()を用いて一掃します。- バージョン 3.5 で変更: - AsyncFunctionDefがサポートされました。
- ast.get_source_segment(source, node, *, padded=False)¶
- Get source code segment of the source that generated node. If some location information ( - lineno,- end_lineno,- col_offset, or- end_col_offset) is missing, return- None.- padded が - Trueの場合、複数行にわたる文の最初の行が元の位置に一致するように空白文字でパディングされます。- Added in version 3.8. 
- ast.fix_missing_locations(node)¶
- When you compile a node tree with - compile(), the compiler expects- linenoand- col_offsetattributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at node.
- ast.increment_lineno(node, n=1)¶
- node で始まるツリー内の各ノードの行番号と終了行番号を n ずつ増やします。これはファイルの中で別の場所に "コードを移動する" ときに便利です。 
- ast.copy_location(new_node, old_node)¶
- Copy source location ( - lineno,- col_offset,- end_lineno, and- end_col_offset) from old_node to new_node if possible, and return new_node.
- ast.iter_fields(node)¶
- node にある - node._fieldsのそれぞれのフィールドを- (フィールド名, 値)のタプルとして yield します。
- ast.iter_child_nodes(node)¶
- node の直接の子ノード全てを yield します。すなわち、yield されるのは、ノードであるような全てのフィールドおよびノードのリストであるようなフィールドの全てのアイテムです。 
- ast.walk(node)¶
- node の全ての子孫ノード(node 自体を含む)を再帰的に yield します。順番は決められていません。この関数はノードをその場で変更するだけで文脈を気にしないような場合に便利です。 
- class ast.NodeVisitor¶
- 抽象構文木を渡り歩いてビジター関数を見つけたノードごとに呼び出すノード・ビジターの基底クラスです。この関数は - visit()メソッドに送られる値を返してもかまいません。- このクラスはビジター・メソッドを付け加えたサブクラスを派生させることを意図しています。 - visit(node)¶
- ノードを訪れます。デフォルトの実装では - self.visit_classnameというメソッド (ここで classname はノードのクラス名です) を呼び出すか、そのメソッドがなければ- generic_visit()を呼び出します。
 - generic_visit(node)¶
- このビジターはノードの全ての子について - visit()を呼び出します。- 注意して欲しいのは、専用のビジター・メソッドを具えたノードの子ノードは、このビジターが - generic_visit()を呼び出すかそれ自身で子ノードを訪れない限り訪れられないということです。
 - visit_Constant(node)¶
- Handles all constant nodes. 
 - トラバースの途中でノードを変化させたいならば - NodeVisitorを使ってはいけません。そうした目的のために変更を許す特別なビジター (- NodeTransformer) があります。- バージョン 3.8 で非推奨: Methods - visit_Num(),- visit_Str(),- visit_Bytes(),- visit_NameConstant()and- visit_Ellipsis()are deprecated now and will not be called in future Python versions. Add the- visit_Constant()method to handle all constant nodes.
- class ast.NodeTransformer¶
- NodeVisitorのサブクラスで抽象構文木を渡り歩きながらノードを変更することを許すものです。- NodeTransformerは抽象構文木(AST)を渡り歩き、ビジター・メソッドの戻り値を使って古いノードを置き換えたり削除したりします。ビジター・メソッドの戻り値が- Noneならば、ノードはその場から取り去られ、そうでなければ戻り値で置き換えられます。置き換えない場合は戻り値が元のノードそのものであってもかまいません。- それでは例を示しましょう。Name (たとえば - foo) を見つけるたび全て- data['foo']に書き換える変換器 (transformer) です:- class RewriteName(NodeTransformer): def visit_Name(self, node): return Subscript( value=Name(id='data'), slice=Constant(value=node.id), ctx=node.ctx ) - Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the - generic_visit()method for the node first.- 文のコレクションであるようなノード (全ての文のノードが当てはまります) に対して、このビジターは単独のノードではなくノードのリストを返すかもしれません。 - If - NodeTransformerintroduces new nodes (that weren't part of original tree) without giving them location information (such as- lineno),- fix_missing_locations()should be called with the new sub-tree to recalculate the location information:- 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, show_empty=False)¶
- node 内のツリーのフォーマットされたダンプを返します。主な使い道はデバッグです。 annotate_fields が true の場合 (デフォルト)、返される文字列はフィールドの名前と値を示します。 annotate_fields が false の場合、あいまいさのないフィールド名を省略することにより、結果文字列はよりコンパクトになります。行番号や列オフセットのような属性はデフォルトではダンプされません。これが必要であれば、 include_attributes を true にすると表示できます。 - indent が非負の整数または文字列の場合、ツリーは指定されたインデントレベルで整形されて出力されます (pretty-printed)。インデントレベルがゼロ、負の数、または - ""の場合は改行だけを挿入します。- None(デフォルト値) は単一行での表記になります。正の整数を指定すると各インデントレベルでその数だけの空白でインデントされます。 indent が文字列 (- "\t"など) の場合、その文字列が各レベルのインデントに使われます。- If show_empty is false (the default), optional empty lists and - Load()values will be omitted from the output. Optional- Nonevalues are always omitted.- >>> tree = ast.parse('print(None)', '?', 'eval') >>> print(ast.dump(tree, indent=4)) Expression( body=Call( func=Name(id='print'), args=[ Constant(value=None)])) >>> print(ast.dump(tree, indent=4, show_empty=True)) Expression( body=Call( func=Name(id='print', ctx=Load()), args=[ Constant(value=None)], keywords=[])) - バージョン 3.9 で変更: indent オプションを追加しました。 - バージョン 3.13 で変更: Added the show_empty option. - バージョン 3.15 で変更: Omit optional - Load()values by default.
Compiler flags¶
以下のフラグはプログラムのコンパイルにおける効果を変更するために compile() に渡すことができます:
- ast.PyCF_ALLOW_TOP_LEVEL_AWAIT¶
- トップレベルの - await,- async for,- async withおよび async 内包表記のサポートを有効化します。- Added in version 3.8. 
- ast.PyCF_ONLY_AST¶
- コンパイルされたコードオブジェクトの代わりに抽象構文木を生成して返します。 
- ast.PyCF_OPTIMIZED_AST¶
- The returned AST is optimized according to the optimize argument in - compile()or- ast.parse().- Added in version 3.13. 
- ast.PyCF_TYPE_COMMENTS¶
- PEP 484 および PEP 526 形式の型コメント ( - # type: <type>,- # type: ignore <stuff>) のサポートを有効化します。- Added in version 3.8. 
- ast.compare(a, b, /, *, compare_attributes=False)¶
- Recursively compares two ASTs. - compare_attributes affects whether AST attributes are considered in the comparison. If compare_attributes is - False(default), then attributes are ignored. Otherwise they must all be equal. This option is useful to check whether the ASTs are structurally equal but differ in whitespace or similar details. Attributes include line numbers and column offsets.- Added in version 3.14. 
コマンドラインでの使用¶
Added in version 3.9.
ast モジュールはコマンドラインからスクリプトとして実行することができます。実行方法は単純です:
python -m ast [-m <mode>] [-a] [infile]
以下のオプションが使用できます:
- -h, --help¶
- ヘルプメッセージを表示して終了します。 
- --no-type-comments¶
- 型コメントをパースしません。 
- -a, --include-attributes¶
- 行番号や列オフセットなどの属性を含めます。 
- --feature-version <version>¶
- Python version in the format 3.x (for example, 3.10). Defaults to the current version of the interpreter. - Added in version 3.14. 
- -O <level>¶
- --optimize <level>¶
- Optimization level for parser. Defaults to no optimization. - Added in version 3.14. 
- --show-empty¶
- Show empty lists and fields that are - None. Defaults to not showing empty objects.- Added in version 3.14. 
infile を指定するとその内容が AST にパースされて標準出力に出力されます。そうでない場合は標準入力から入力を読み込みます。
参考
外部ドキュメント Green Tree Snakes には Python AST についての詳細が書かれています。
ASTTokens は Python AST を、生成元のソースコードのトークン位置やテキストで注解します。これはソースコード変換を行うツールで有用です。
leoAst.py unifies the token-based and parse-tree-based views of python programs by inserting two-way links between tokens and ast nodes.
LibCST はコードを ast ツリーに似た構文木 (Concrete Syntax Tree) にパースし、かつ全ての書式設定の詳細を保持します。これは自動リファクタリングアプリケーション (codemod) やリンタを作成する際に有用です。
Parso is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python versions). Parso is also able to list multiple syntax errors in your Python file.