ast — 추상 구문 트리

소스 코드: Lib/ast.py


ast 모듈은 파이썬 응용 프로그램이 파이썬 추상 구문 문법의 트리를 처리하는 데 도움을 줍니다. 추상 구문 자체는 각 파이썬 릴리스마다 바뀔 수 있습니다; 이 모듈은 프로그래밍 방식으로 현재 문법의 모양을 찾는 데 도움이 됩니다.

ast.PyCF_ONLY_AST를 플래그로 compile() 내장 함수에 전달하거나, 이 모듈에서 제공된 parse() 도우미를 사용하여 추상 구문 트리를 생성할 수 있습니다. 결과는 클래스가 모두 ast.AST에서 상속되는 객체들의 트리가 됩니다. 내장 compile() 함수를 사용하여 추상 구문 트리를 파이썬 코드 객체로 컴파일할 수 있습니다.

추상 문법

추상 문법은 현재 다음과 같이 정의됩니다:

-- 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)
         | 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)
             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)
               | ParamSpec(identifier name)
               | TypeVarTuple(identifier name)
               attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
}

노드 클래스

class ast.AST

This is the base of all AST node classes. The actual node classes are derived from the Parser/Python.asdl file, which is reproduced above. They are defined in the _ast C module and re-exported in ast.

추상 문법의 각 좌변 심볼마다 하나의 클래스가 정의되어 있습니다 (예를 들어, ast.stmtast.expr). 또한, 우변의 생성자마다 하나의 클래스가 정의되어 있습니다; 이 클래스는 좌변 트리의 클래스에서 상속됩니다. 예를 들어, ast.BinOpast.expr에서 상속됩니다. 대안을 갖는 생성 규칙(일명 “합”)의 경우, 좌변 클래스는 추상입니다: 특정 생성자 노드의 인스턴스만 만들어집니다.

_fields

각 구상 클래스에는 모든 자식 노드의 이름을 제공하는 어트리뷰트 _fields가 있습니다.

구상 클래스의 각 인스턴스에는 각 자식 노드마다 문법에 정의된 형의 어트리뷰트가 하나씩 있습니다. 예를 들어, ast.BinOp 인스턴스는 ast.expr 형의 어트리뷰트 left를 갖습니다.

문법에서 이러한 어트리뷰트가 선택적으로 표시되면 (물음표를 사용해서), 값은 None일 수 있습니다. 어트리뷰트가 0개 이상의 값을 가질 수 있으면 (애스터리스크로 표시됩니다), 값은 파이썬 리스트로 표현됩니다. compile()로 AST를 컴파일할 때 가능한 모든 어트리뷰트가 존재하고 유효한 값을 가져야 합니다.

lineno
col_offset
end_lineno
end_col_offset

Instances of ast.expr and ast.stmt subclasses have lineno, col_offset, end_lineno, and end_col_offset attributes. The lineno and end_lineno are the first and last line numbers of source text span (1-indexed so the first line is line 1) and the col_offset and end_col_offset are the corresponding UTF-8 byte offsets of the first and last tokens that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.

종료 위치는 컴파일러에 필요하지 않아서 선택 사항입니다. 종료 오프셋은 마지막 심볼 입니다. 예를 들어 source_line[node.col_offset : node.end_col_offset]를 사용하여 한 줄 표현식 노드의 소스 세그먼트를 가져올 수 있습니다.

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부터 폐지됨: 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.

참고

여기에 표시된 특정 노드 클래스에 대한 설명은 처음에는 환상적인 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.

body is a list of the module’s 문장.

type_ignores is a list of 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))],
    type_ignores=[])
class ast.Expression(body)

A single Python expression input. Node type generated by ast.parse() when mode is "eval".

body is 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".

body is a list of 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

argtypes is a list of expression nodes.

returns is a single expression node.

>>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4))
FunctionType(
    argtypes=[
        Name(id='int', ctx=Load()),
        Name(id='str', ctx=Load())],
    returns=Subscript(
        value=Name(id='List', ctx=Load()),
        slice=Name(id='int', ctx=Load()),
        ctx=Load()))

버전 3.8에 추가.

리터럴

class ast.Constant(value)

상숫값. Constant 리터럴의 value 어트리뷰트는 그것이 나타내는 파이썬 객체를 포함합니다. 표현되는 값은 숫자, 문자열 또는 None과 같은 간단한 형일 수 있지만, 모든 요소가 상수라면 불변 컨테이너 형(튜플과 frozenset)일 수도 있습니다.

>>> 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입니다. conversionformat_spec을 동시에 설정할 수 있습니다.

class ast.JoinedStr(values)

일련의 FormattedValueConstant 노드로 구성된 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는 컨테이너가 대입 대상이면 (가령 (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)],
        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)

딕셔너리. keysvalues는 각각 키와 값을 나타내는 노드의 리스트를 일치하는 순서대로 (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', 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 노드)를 보유합니다. 이 형은 *argsCall 노드를 빌드할 때 사용해야 합니다.

>>> 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는 이 섹션의 다른 노드인 Constant, Name, Lambda, Yield 또는 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

단항 연산자 토큰. Notnot 키워드이고, 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는 연산자이고, leftright는 임의의 표현식 노드입니다.

>>> 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)

불리언 연산, ‘or’ 나 ‘and’. opOrAnd입니다. values는 관련된 값입니다. 같은 연산자를 사용하는 연속 연산(가령 a or b or c)은 여러 값을 가진 하나의 노드로 축소됩니다.

여기에는 UnaryOpnot이 포함되지 않습니다.

>>> 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)

둘 이상의 값의 비교. 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)

함수 호출. func는 함수이며, 종종 Name이나 Attribute 객체입니다. 인자 중:

  • args는 위치로 전달된 인자의 리스트를 보유합니다.

  • keywords holds a list of keyword objects representing arguments passed by keyword.

When creating a Call node, args and keywords are required, but they can be empty lists.

>>> 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와 같은 표현식. 각 필드는 단일 노드를 보유해서, 다음 예에서, 세 개 모두 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 노드는 대입 표현식 연산자(바다코끼리(walrus) 연산자라고도 합니다)에 의해 생성됩니다. 첫 번째 인자가 여러 노드일 수 있는 Assign 노드와 달리, 이 경우에는 targetvalue는 모두 단일 노드여야 합니다.

>>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
Expression(
    body=NamedExpr(
        target=Name(id='x', ctx=Store()),
        value=Constant(value=4)))

버전 3.8에 추가.

서브스크립팅

class ast.Subscript(value, slice, ctx)

서브스크립트, 가령 l[1]. value는 서브스크립트되는 객체입니다 (보통 시퀀스나 매핑). slice는 인덱스, 슬라이스 또는 키입니다. Tuple일 수 있으며 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:upperlower:upper:step 형식). Subscriptslice 필드 내에서만 직접 또는 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(또는 keyvalue)는 항목마다 평가될 부분을 나타내는 단일 노드입니다.

generatorscomprehension 노드의 리스트입니다.

>>> 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)

컴프리헨션에서 하나의 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 내에 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))],
    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은 단일 노드이며 Name, Attribute 또는 Subscript일 수 있습니다. annotationConstantName 노드와 같은 어노테이션입니다. value는 단일 선택적 노드입니다. simple은 괄호 사이에 나타나지 않은 순수한 이름이며 표현식이 아닌 targetName 노드에 대해 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. 다음 예에서, targetx(Store 컨텍스트로)를 위한 Name 노드이고, opAdd이며, value는 값이 1인 Constant입니다.

The target attribute cannot be of class Tuple or List, unlike the targets of Assign.

>>> 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입니다. causeraise 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 문을 나타냅니다. targetsName, 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.TypeAlias(name, type_params, value)

A type alias created through the type statement. name is the name of the alias, type_params is a list of type parameters, and value is 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()),
            type_params=[],
            value=Name(id='int', ctx=Load()))],
    type_ignores=[])

버전 3.12에 추가.

함수나 루프 내부에만 적용할 수 있는 다른 문장들은 다른 섹션에 설명되어 있습니다.

임포트

class ast.Import(names)

import 문. namesalias 노드의 리스트입니다.

>>> 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)

두 매개 변수 모두 이름의 원시 문자열입니다. 정규 이름을 사용하면 asnameNone이 될 수 있습니다.

>>> 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 노드와 같은) 단일 노드를 보유합니다. bodyorelse는 각각 노드 리스트를 보유합니다.

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)

A for loop. target holds the variable(s) the loop assigns to, as a single Name, Tuple, List, Attribute or Subscript node. iter holds the item to be looped over, again as a single node. body and orelse contain lists of nodes to execute. Those in orelse are executed if the loop finishes normally, rather than via a break statement.

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

breakcontinue 문.

>>> 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.TryStar(body, handlers, orelse, finalbody)

try blocks which are followed by except* clauses. The attributes are the same as for Try but the ExceptHandler nodes in handlers are 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', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])],
            orelse=[],
            finalbody=[])],
    type_ignores=[])

버전 3.11에 추가.

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_varsas 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', 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=[])

Pattern matching

class ast.Match(subject, cases)

A match statement. subject holds the subject of the match (the object that is being matched against the cases) and cases contains an iterable of match_case nodes with the different cases.

버전 3.10에 추가.

class ast.match_case(pattern, guard, body)

A single case pattern in a match statement. pattern contains the match pattern that the subject will be matched against. Note that the AST nodes produced for patterns differ from those produced for expressions, even when they share the same syntax.

The guard attribute contains an expression that will be evaluated if the pattern matches the subject.

body contains 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', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchAs(name='x')]),
                    guard=Compare(
                        left=Name(id='x', ctx=Load()),
                        ops=[
                            Gt()],
                        comparators=[
                            Constant(value=0)]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='tuple', ctx=Load()),
                        patterns=[],
                        kwd_attrs=[],
                        kwd_patterns=[]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])

버전 3.10에 추가.

class ast.MatchValue(value)

A match literal or value pattern that compares by equality. value is 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', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchValue(
                        value=Constant(value='Relevant')),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])

버전 3.10에 추가.

class ast.MatchSingleton(value)

A match literal pattern that compares by identity. value is 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', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSingleton(value=None),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])

버전 3.10에 추가.

class ast.MatchSequence(patterns)

A match sequence pattern. patterns contains 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 MatchStar node, 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', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchSequence(
                        patterns=[
                            MatchValue(
                                value=Constant(value=1)),
                            MatchValue(
                                value=Constant(value=2))]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])

버전 3.10에 추가.

class ast.MatchStar(name)

Matches the rest of the sequence in a variable length match sequence pattern. If name is 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', ctx=Load()),
            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))])])],
    type_ignores=[])

버전 3.10에 추가.

class ast.MatchMapping(keys, patterns, rest)

A match mapping pattern. keys is a sequence of expression nodes. patterns is a corresponding sequence of pattern nodes. rest is 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 rest is 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', ctx=Load()),
            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(keys=[], patterns=[], rest='rest'),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])

버전 3.10에 추가.

class ast.MatchClass(cls, patterns, kwd_attrs, kwd_patterns)

A match class pattern. cls is an expression giving the nominal class to be matched. patterns is a sequence of pattern nodes to be matched against the class defined sequence of pattern matching attributes. kwd_attrs is a sequence of additional attributes to be matched (specified as keyword arguments in the class pattern), kwd_patterns are 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', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='Point2D', ctx=Load()),
                        patterns=[
                            MatchValue(
                                value=Constant(value=0)),
                            MatchValue(
                                value=Constant(value=0))],
                        kwd_attrs=[],
                        kwd_patterns=[]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                match_case(
                    pattern=MatchClass(
                        cls=Name(id='Point3D', ctx=Load()),
                        patterns=[],
                        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))])])],
    type_ignores=[])

버전 3.10에 추가.

class ast.MatchAs(pattern, name)

A match “as-pattern”, capture pattern or wildcard pattern. pattern contains 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 name attribute contains the name that will be bound if the pattern is successful. If name is None, pattern must also be None and 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', ctx=Load()),
            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))])])],
    type_ignores=[])

버전 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 patterns attribute 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', ctx=Load()),
            cases=[
                match_case(
                    pattern=MatchOr(
                        patterns=[
                            MatchSequence(
                                patterns=[
                                    MatchAs(name='x')]),
                            MatchAs(name='y')]),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])],
    type_ignores=[])

버전 3.10에 추가.

Type parameters

Type parameters can exist on classes, functions, and type aliases.

class ast.TypeVar(name, bound)

A typing.TypeVar. name is the name of the type variable. bound is the bound or constraints, if any. If bound is a Tuple, it represents constraints; otherwise it represents the bound.

>>> print(ast.dump(ast.parse("type Alias[T: int] = list[T]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                TypeVar(
                    name='T',
                    bound=Name(id='int', ctx=Load()))],
            value=Subscript(
                value=Name(id='list', ctx=Load()),
                slice=Name(id='T', ctx=Load()),
                ctx=Load()))],
    type_ignores=[])

버전 3.12에 추가.

class ast.ParamSpec(name)

A typing.ParamSpec. name is the name of the parameter specification.

>>> print(ast.dump(ast.parse("type Alias[**P] = Callable[P, int]"), indent=4))
Module(
    body=[
        TypeAlias(
            name=Name(id='Alias', ctx=Store()),
            type_params=[
                ParamSpec(name='P')],
            value=Subscript(
                value=Name(id='Callable', ctx=Load()),
                slice=Tuple(
                    elts=[
                        Name(id='P', ctx=Load()),
                        Name(id='int', ctx=Load())],
                    ctx=Load()),
                ctx=Load()))],
    type_ignores=[])

버전 3.12에 추가.

class ast.TypeVarTuple(name)

A typing.TypeVarTuple. name is the name of the type variable tuple.

>>> 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')],
            value=Subscript(
                value=Name(id='tuple', ctx=Load()),
                slice=Tuple(
                    elts=[
                        Starred(
                            value=Name(id='Ts', ctx=Load()),
                            ctx=Load())],
                    ctx=Load()),
                ctx=Load()))],
    type_ignores=[])

버전 3.12에 추가.

함수와 클래스 정의

class ast.FunctionDef(name, args, body, decorator_list, returns, type_comment, type_params)

함수 정의.

  • name은 함수 이름의 원시 문자열입니다.

  • args is an arguments node.

  • body는 함수 내부의 노드 리스트입니다.

  • decorator_list는 적용할 데코레이터 리스트이며, 가장 바깥쪽에 먼저 저장됩니다 (즉, 리스트의 첫 번째가 마지막에 적용됩니다).

  • returns는 반환 어노테이션입니다.

  • type_params is 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(
                    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)

함수의 인자.

  • posonlyargs, argskwonlyargsarg 노드의 리스트입니다.

  • varargkwarg*args, **kwargs 매개 변수를 참조하는 단일 arg 노드입니다.

  • kw_defaults는 키워드 전용 인자의 기본값 리스트입니다. 어떤 것이 None이면, 해당 인자는 필수입니다.

  • defaults는 위치적으로 전달될 수 있는 인자의 기본값 리스트입니다. 기본값 수가 더 적으면, 마지막 n개의 인자에 해당합니다.

class ast.arg(arg, annotation, type_comment)

A single argument in a list. arg is a raw string of the argument name; annotation is its annotation, such as a Name node.

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_params=[])],
    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)

yieldyield 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)

globalnonlocal 문. 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, body, decorator_list, type_params)

클래스 정의.

  • name은 클래스 이름의 원시 문자열입니다.

  • bases는 명시적으로 지정된 베이스 클래스의 노드 리스트입니다.

  • keywords is a list of keyword nodes, principally for ‘metaclass’. Other keywords will be passed to the metaclass, as per PEP-3115.

  • body는 클래스 정의 내에서 코드를 나타내는 노드 리스트입니다.

  • decorator_listFunctionDef에서와 같이 노드 리스트입니다.

  • type_params is 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', 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_params=[])],
    type_ignores=[])

버전 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의 본문에서만 유효합니다.

>>> 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_params=[])],
    type_ignores=[])
class ast.AsyncFor(target, iter, body, orelse, type_comment)
class ast.AsyncWith(items, body, type_comment)

async for 루프와 async with 컨텍스트 관리자. 이들은 각각 ForWith와 같은 필드를 갖습니다. AsyncFunctionDef의 본문에서만 유효합니다.

참고

문자열이 ast.parse()로 구문 분석될 때, 반환된 트리의 연산자 노드(ast.operator, ast.unaryop, ast.cmpop, ast.boolopast.expr_context의 서브 클래스)는 싱글톤이 됩니다. 어느 하나의 변경 사항은 같은 값으로 등장하는 다른 모든 곳에 반영됩니다 (예를 들어 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 484PEP 526에 지정된 형 주석을 확인하고 반환하도록 수정됩니다. 이는 compile()에 전달된 플래그에 ast.PyCF_TYPE_COMMENTS를 추가하는 것과 같습니다. 이것은 잘못 배치된 형 주석에 대한 문법 에러를 보고합니다. 이 플래그가 없으면, 형 주석은 무시되고, 선택한 AST 노드의 type_comment 필드는 항상 None입니다. 또한, # type: ignore 주석의 위치는 Moduletype_ignores 어트리뷰트로 반환됩니다 (그렇지 않으면 항상 빈 리스트입니다).

또한, mode'func_type'이면, 입력 문법은 PEP 484 “서명 형 주석”에 따라 수정됩니다, 예를 들어 (str, int) -> List[str].

Setting feature_version to 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 match statements. Currently major must equal to 3. The lowest supported version is (3, 4) (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), ValueError is 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 SyntaxError exceptions. For instance, the source return 42 generates 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.

경고

파이썬 AST 컴파일러의 스택 깊이 제한으로 인해 충분히 크고/복잡한 문자열로 파이썬 인터프리터가 충돌하도록 만들 수 있습니다.

버전 3.8에서 변경: type_comments, mode='func_type'feature_version추가했습니다.

ast.unparse(ast_obj)

ast.AST 객체를 역 구문 분석하고 ast.parse()로 다시 구문 분석할 경우 동등한 ast.AST 객체를 생성하는 코드가 포함된 문자열을 생성합니다.

경고

생성된 코드 문자열은 ast.AST 객체를 생성한 원래 코드와 반드시 같을 필요는 없습니다 (상수 튜플/frozenset과 같은 컴파일러 최적화 없이).

경고

매우 복잡한 표현식을 역 구분 분석하려고 하면 RecursionError가 발생할 수 있습니다.

버전 3.9에 추가.

ast.literal_eval(node_or_string)

Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.

This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

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.

경고

It is possible to crash the Python interpreter due to stack depth limitations in Python’s AST compiler.

It can raise ValueError, TypeError, SyntaxError, MemoryError and RecursionError depending 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.

paddedTrue이면, 여러 줄 문장의 첫 번째 줄은 원래 위치와 일치하도록 스페이스로 채워집니다.

버전 3.8에 추가.

ast.fix_missing_locations(node)

When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes 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의 각 필드에 대해 (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()를 호출하거나 직접 방문하지 않는 한, 사용자 정의 방문자 메서드가 있는 노드의 자식 노드는 방문 되지 않음에 유의하십시오.

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이면, 노드가 그 위치에서 제거되고, 그렇지 않으면 반환 값으로 치환됩니다. 반환 값은 원래 노드일 수 있으며, 이때는 치환이 일어나지 않습니다.

다음은 모든 이름 조회(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
        )

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 NodeTransformer introduces 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)

node에서 포맷된 트리 덤프를 반환합니다. 이것은 주로 디버깅 목적으로 유용합니다. annotate_fields가 참이면 (기본값), 반환된 문자열에 필드의 이름과 값이 표시됩니다. annotate_fields가 거짓이면, 모호하지 않은 필드 이름을 생략하여 결과 문자열이 더 간결해집니다. 줄 번호와 열 오프셋과 같은 어트리뷰트는 기본적으로 덤프 되지 않습니다. 원한다면, include_attributes를 참으로 설정할 수 있습니다.

indent가 음이 아닌 정수나 문자열이면, 트리는 그 들여쓰기 수준으로 예쁘게 인쇄됩니다. 들여쓰기 수준 0, 음수 또는 ""는 줄 넘김 만 삽입합니다. None(기본값)은 단일 줄 표현을 선택합니다. 양의 정수 indent를 사용하면 수준마다 그만큼 들여쓰기 됩니다. indent가 문자열(가령 "\t")이면, 해당 문자열은 각 수준을 들여 쓰는 데 사용됩니다.

버전 3.9에서 변경: indent 옵션을 추가했습니다.

컴파일러 플래그

프로그램 컴파일에 대한 효과를 변경하기 위해 다음 플래그를 compile()에 전달할 수 있습니다:

ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

최상위 수준 await, async for, async with 및 비동기 컴프리헨션에 대한 지원을 활성화합니다.

버전 3.8에 추가.

ast.PyCF_ONLY_AST

컴파일된 코드 객체를 반환하는 대신 추상 구문 트리를 생성하고 반환합니다.

ast.PyCF_TYPE_COMMENTS

PEP 484PEP 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, 파이썬 AST로 작업하는 것에 대한 자세한 내용이 있는 외부 문서 자원.

ASTTokens는 토큰의 위치와 토큰을 생성한 소스 코드의 텍스트로 파이썬 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) 응용 프로그램과 린터(linter)를 구축하는 데 유용합니다.

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.