Python

ast — 추상 구문 트리

소스 코드: Lib/ast.py


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

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

추상 문법

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

-- ASDL의 4가지 내장 타입:
-- 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'은 괄호 없이 단순한 이름을 주석으로 단다는 것을 나타냅니다
          | AnnAssign(expr target, expr annotation, expr? value, int simple)

          -- else가 대상 언어의 키워드이므로 'orelse'를 사용합니다
          | 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, int? is_lazy)
          | ImportFrom(identifier? module, alias* names, int? level, int? is_lazy)

          | Global(identifier* names)
          | Nonlocal(identifier* names)
          | Expr(expr value)
          | Pass | Break | Continue

          -- col_offset은 파서가 사용하는 utf8 문자열의 바이트 오프셋입니다
          attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

          -- BoolOp()에서 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)
         -- 문법적으로 yield 표현식이 나타날 수 있는 위치가 제한됩니다
         | Await(expr value)
         | Yield(expr? value)
         | YieldFrom(expr value)
         -- x < 4 < 3과 (x < 4) < 3을 구분하기 위해
         -- 비교(compare) 시퀀스가 필요합니다
         | 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)

         -- 다음 표현식은 할당 문맥에 나타날 수 있습니다
         | 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)

         -- Subscript에서만 나타날 수 있습니다
         | Slice(expr? lower, expr? upper, expr? step)

          -- col_offset은 파서가 사용하는 utf8 문자열의 바이트 오프셋입니다
          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)

    -- 호출 시 제공되는 키워드 인자 (**kwargs의 경우 identifier가 NULL임)
    keyword = (identifier? arg, expr value)
               attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

    -- 선택적인 '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)
            -- 선택적인 "rest" MatchMapping 매개변수는 추가적인 매핑 키 캡처를 처리합니다

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

노드 클래스

class ast.AST

이것은 모든 AST 노드 클래스의 추상 기본 클래스입니다. 실제 노드 클래스는 Parser/Python.asdl 파일에서 파생되며, 여기서는 above <abstract-grammar>`에 재현됩니다. 이들은 :mod:!_ast` C 모듈에 정의되어 있고 :mod:`!ast`에서 재내보내집니다.

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

_fields

각 구체적인 클래스는 모든 자식 노드의 이름을 제공하는 _fields 속성을 가집니다.

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

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

_field_types

각 구체적인 클래스에 있는 _field_types 속성은 필드 이름(또한 :attr:`_fields`에 나열된)을 해당 타입으로 매핑하는 딕셔너리입니다.

>>> 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.exprast.stmt 서브클래스의 인스턴스는 lineno, col_offset, end_lineno, 및 end_col_offset 속성을 가집니다. linenoend_lineno`는 소스 텍스트 범위의 번째 마지막 라인 번호(1부터 인덱싱되어 번째 라인은 1번)이며, :attr:`col_offset 및 :attr:`end_col_offset`는 노드를 생성한 첫 번째 및 마지막 토큰에 해당하는 UTF-8 바이트 오프셋입니다. 파서가 내부적으로 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)

문법에서 선택적 필드가 생성자에서 생략되면 기본값은 None 입니다. 리스트 필드가 생략되면 기본값은 빈 리스트입니다. ast.expr_context 타입 필드가 생략되면 기본값은 Load() 가 됩니다. 다른 필드가 생략되면 DeprecationWarning 이 발생하며 AST 노드에는 해당 필드가 없습니다. Python 3.15에서는 이 조건이 오류를 발생시킵니다.

버전 3.8에서 변경: ast.Constant 클래스는 이제 모든 상수에 사용됩니다.

버전 3.9에서 변경: 단순 인덱스는 값으로 표현되고, 확장 슬라이스는 튜플로 표현됩니다.

버전 3.13에서 변경: AST 노드 생성자가 생략된 필드에 대한 합리적인 기본값을 제공하도록 변경되었습니다. 선택적 필드는 이제 기본값이 None 이며, 리스트 필드는 빈 리스트를 기본값으로 하고, ast.expr_context 타입 필드는 Load() 를 기본값으로 합니다. 이전에 생략된 속성은 생성된 노드에 존재하지 않았습니다(접근 시 AttributeError 발생).

버전 3.14에서 변경: AST 노드의 __repr__() 출력에는 노드 필드의 값이 포함됩니다.

버전 3.8에서 폐지되었고, 버전 3.14에서 제거됩니다: 이전 버전의 Python은 Python 3.8에서 사용 중단된 AST 클래스 ast.Num, ast.Str, ast.Bytes, ast.NameConstant 및 :class:`!ast.Ellipsis`를 제공했습니다. 이 클래스들은 Python 3.14에서 제거되었으며, 그 기능은 :class:`ast.Constant`로 대체되었습니다.

버전 3.9부터 폐지됨: 구형 클래스 ast.Index`와 :class:!ast.ExtSlice`는 여전히 사용할 수 있지만, 향후 Python 릴리스에서 제거될 예정입니다. 그동안 인스턴스화하면 다른 클래스의 인스턴스가 반환됩니다.

버전 3.13에서 폐지되었고, 버전 3.15에서 제거됩니다: 이전 버전의 Python은 필수 필드가 누락된 AST 노드의 생성을 허용했습니다. 마찬가지로 AST 노드 생성자는 AST 노드의 필드와 일치하지 않더라도 속성으로 설정되는 임의의 키워드 인자를 허용했습니다. 이러한 경우들은 이제 :exc:`TypeError`를 발생시킵니다.

버전 3.15에서 폐지되었고, 버전 3.20에서 제거됩니다: :ref:`above <abstract-grammar>`에서 변형(변형을 의미하는 “합”으로도 알려짐)을 갖는 생산 규칙에 해당하는 AST 노드 클래스는 추상 클래스입니다. 이전 버전의 Python은 이러한 추상 노드 클래스의 직접 인스턴스 생성을 허용했습니다. 이 동작은 사용 중단되었으며 Python 3.20에서 제거될 예정입니다.

참고

여기에 표시된 특정 노드 클래스에 대한 설명은 처음에는 환상적인 Green Tree Snakes 프로젝트와 모든 기여자로부터 차용했습니다.

루트 노드

class ast.Module(body, type_ignores)

Python 모듈은 file input 와 같습니다. 기본 "exec" 모드 에서 ast.parse() 에 의해 생성된 노드 타입입니다.

body 는 해당 모듈의 문장list 입니다.

type_ignores 는 해당 모듈의 타입 무시 주석에 대한 list 입니다. 자세한 내용은 ast.parse() 를 참조하세요.

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

단일 Python expression input 입니다. mode"eval" 일 때 ast.parse() 에 의해 생성된 노드 타입입니다.

body 는 단일 노드이며, 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".

` bodyliststatement 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".

이러한 타입 주석은 다음과 같이 보입니다:

def sum_two_number(a, b):
    # type: (int, int) -> int
    return a + b

argtypeslistexpression nodes 목록입니다.

returns 는 단일 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, kind)

상수 값입니다. Constant 리터럴의 value 속성은 그것을 나타내는 파이썬 객체를 포함합니다. 표현 가능한 값은 str, bytes, int, float, complex, :class:`bool`의 인스턴스일 수 있으며, 상수로는 :data:`None`과 :data:`Ellipsis`가 있습니다.

kind 속성은 선택적 문자열입니다. u 접두사가 있는 문자열 리터럴의 경우, kind'u' 로 설정됩니다. 다른 모든 상수의 경우, kindNone 입니다.

>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
    body=Constant(value=123))
>>> print(ast.dump(ast.parse("u'hello'", mode='eval'), indent=4))
Expression(
    body=Constant(value='hello', kind='u'))
class ast.FormattedValue(value, conversion, format_spec)

f-문자열에서 단일 포매팅 필드를 나타내는 노드. 문자열에 단일 포매팅 필드가 포함되어 있고 다른 것이 없으면 노드를 분리 할 수 있습니다, 그렇지 않으면 JoinedStr에 나타납니다.

  • value는 모든 표현식 노드(가령 리터럴, 변수 또는 함수 호출)입니다.

  • conversion은 정수입니다:

    • -1: 포매팅 없음

    • 97 (ord('a')): !a ASCII 포매팅

    • 114 (ord('r')): !r repr() 포매팅

    • 115 (ord('s')): !s string 포매팅

  • 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'),
                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.

일련의 InterpolationConstant 노드를 포함하는 템플릿 문자열 리터럴을 나타내는 노드입니다. 이 노드들은 순서에 상관없으며 순서대로 배치될 필요는 없습니다.

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

템플릿 문자열 리터럴 내 단일 보간 필드를 나타내는 노드입니다.

  • value 는 모든 표현식 노드(가령 리터럴, 변수, 또는 함수 호출)입니다. 이는 FormattedValue.value 와 동일한 의미를 가집니다.

  • str 은 보간 표현식의 텍스트를 포함하는 상수입니다.

    ` strNone 으로 설정된 경우, ast.unparse() 를 호출할 때 코드를 생성하는 데 value 가 사용됩니다. 이는 더 이상 생성된 코드가 원본과 동일함을 보장하지 않으며 코드 생성을 위한 것입니다.

  • conversion은 정수입니다:

    • -1: 변환 없음

    • 97 (ord('a')): !a ASCII 변환

    • 114 (ord('r')): !r repr() 변환

    • 115 (ord('s')): !s string 변환

    이는 FormattedValue.conversion 과 동일한 의미입니다.

  • format_spec 은 값의 포매팅을 나타내는 JoinedStr 노드이거나, 포맷이 지정되지 않은 경우 None 입니다. conversionformat_spec 을 동시에 설정할 수 있습니다. 이는 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)

집합. 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')]))

변수

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

>>> 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 노드)를 보유합니다. 이 형은 *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'))])

표현식

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

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

>>> 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’. 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'),
            Name(id='y')]))
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'),
            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 는 키워드 인자로 전달된 인자를 나타내는 keyword 객체 목록을 포함합니다.

argskeywords 인자는 선택적이며 기본값은 빈 리스트입니다.

>>> 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와 같은 표현식. 각 필드는 단일 노드를 보유해서, 다음 예에서, 세 개 모두 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 노드는 대입 표현식 연산자(바다코끼리(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)))

Added in version 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'),
        slice=Tuple(
            elts=[
                Slice(
                    lower=Constant(value=1),
                    upper=Constant(value=2)),
                Constant(value=3)])))
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'),
        slice=Slice(
            lower=Constant(value=1),
            upper=Constant(value=2))))

컴프리헨션

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'),
        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는 컴프리헨션이 비동기임을 나타냅니다 (for 대신 async for를 사용합니다). 값은 정수(0이나 1)입니다.

>>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
...                indent=4)) # 여러 컴프리헨션 사용 예시
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)) # 제너레이터 컴프리헨션 예시
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)) # 비동기 컴프리헨션 예시
Expression(
    body=ListComp(
        elt=Name(id='i'),
        generators=[
            comprehension(
                target=Name(id='i', ctx=Store()),
                iter=Name(id='soc'),
                is_async=1)]))

문장

class ast.Assign(targets, value, type_comment)

대입. targets는 노드의 리스트이고, value는 단일 노드입니다.

targets의 여러 노드는 각각 같은 값을 할당하는 것을 나타냅니다. 언 패킹은 targets 내에 Tuple이나 List를 넣어 표현됩니다.

type_comment

type_comment는 형 어노테이션이 주석으로 포함된 선택적 문자열입니다.

[msgid]
>>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # 다중 할당 예시
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)) # 언패킹 예시
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)

[msgid] An assignment with a type annotation. target is a single node and can be a Name, an Attribute or a Subscript. annotation is the annotation, such as a Constant or Name node. value is a single optional node.

[msgid] simple is always either 0 (indicating a “complex” target) or 1 (indicating a “simple” target). A “simple” target consists solely of a Name node that does not appear between parentheses; all other targets are considered complex. Only simple targets appear in the __annotations__ dictionary of modules and classes.

[msgid]
>>> 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. 다음 예에서, targetx(Store 컨텍스트로)를 위한 Name 노드이고, opAdd이며, value는 값이 1인 Constant입니다.

[msgid] 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))])
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'),
            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 문을 나타냅니다. 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())])])
class ast.Pass

pass 문.

>>> print(ast.dump(ast.parse('pass'), indent=4))
Module(
    body=[
        Pass()])
class ast.TypeAlias(name, type_params, value)

[msgid] 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()),
            value=Name(id='int'))])

Added in version 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')],
            is_lazy=0)])
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,
            is_lazy=0)])
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,
            is_lazy=0)])

제어 흐름

참고

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

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

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

[msgid] 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'),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])

Added in version 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'),
                        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_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'),
                    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')]))])])

[msgid] Pattern matching

class ast.Match(subject, cases)

[msgid] 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.

Added in version 3.10.

class ast.match_case(pattern, guard, body)

[msgid] 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.

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

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

[msgid] 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'),
            cases=[
                match_case(
                    pattern=MatchValue(
                        value=Constant(value='Relevant')),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])

Added in version 3.10.

class ast.MatchSingleton(value)

[msgid] 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'),
            cases=[
                match_case(
                    pattern=MatchSingleton(value=None),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])])])

Added in version 3.10.

class ast.MatchSequence(patterns)

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

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

[msgid] 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.

이 패턴은 subject가 매핑(mapping)이고, 평가된 모든 키 표현이 매핑에 존재하며, 각 키에 해당하는 값이 해당 하위 패턴과 일치할 때 성공합니다. restNone 이 아니면, 전체 매핑 패턴이 성공할 때 나머지 매핑 요소를 담는 딕셔너리가 해당 이름에 바인딩됩니다.

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

매치 클래스 패턴입니다. cls 는 매치할 명시적 클래스를 나타내는 표현식입니다. patterns 는 클래스가 정의한 패턴 매칭 속성이 정의된 순서에 맞춰 매치할 패턴 노드의 시퀀스입니다. kwd_attrs 는 매치할 추가 속성의 시퀀스입니다 (클래스 패턴의 키워드 인수로 지정). kwd_patterns 는 해당 패턴에 해당하는 패턴입니다 (클래스 패턴의 키워드 값으로 지정).

이 패턴은 subject가 지명된 클래스의 인스턴스이고, 모든 위치 패턴이 해당 클래스 정의 속성과 일치하며, 지정된 모든 키워드 속성이 해당 패턴과 일치할 때 성공합니다.

참고: 클래스는 패턴 노드를 매치하기 위해 self를 반환하는 속성을 정의할 수 있습니다. 여러 내장 타입도 매치 조건 문서에 설명된 방식처럼 이런 식으로 매치됩니다.

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

매치 구문 as-pattern, 캡처 패턴, 또는 와일드카드 패턴입니다. pattern 은 subject가 매치될 매치 패턴을 담고 있습니다. 패턴이 None 인 경우, 해당 노드는 캡처 패턴(즉, 빈 이름)을 나타내며 항상 성공합니다.

name 속성에는 패턴이 성공할 경우 바인딩될 이름이 포함됩니다. nameNone 이면, patternNone 이어야 하며 해당 노드는 와일드카드 패턴을 나타냅니다.

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

매치 or-pattern``입니다. or-pattern은 sub-pattern 각각을 순차적으로 subject에 매치하여, 하나라도 성공할 때까지 시도됩니다. then or-pattern이 성공으로 간주됩니다. 어떤 sub-pattern도 성공하지 못하면 or-pattern은 실패합니다. ``patterns 속성에는 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.

타입 주석

class ast.TypeIgnore(lineno, tag)

lineno 에서 위치한 # type: ignore 주석입니다. tag# 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]')])

참고

TypeIgnore 노드는 type_comments 매개변수가 False (기본값)로 설정된 경우 생성되지 않습니다. 자세한 내용은 ast.parse() 를 참조하십시오.

Added in version 3.8.

형 매개변수

:ref:`Type parameters <type-params>`는 클래스, 함수, 타입 별칭에 존재할 수 있습니다.

class ast.TypeVar(name, bound, default_value)

typing.TypeVar. name 은 타입 변수의 이름입니다. bound 는 바운드 또는 제약 조건이며, 있다면 해당합니다. boundTuple 인 경우, 이는 제약 조건을 나타내며, 그렇지 않은 경우 바운드를 나타냅니다. default_value 는 기본값이며, TypeVar 에 기본값이 없는 경우 이 속성은 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에서 변경: default_value 매개변수가 추가되었습니다.

class ast.ParamSpec(name, default_value)

typing.ParamSpec. name 은 매개변수 사양의 이름입니다. default_value 는 기본값이며, ParamSpec 에 기본값이 없는 경우 이 속성은 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에서 변경: default_value 매개변수가 추가되었습니다.

class ast.TypeVarTuple(name, default_value)

typing.TypeVarTuple. name 은 타입 변수 튜플의 이름입니다. default_value 는 기본값이며, TypeVarTuple 에 기본값이 없는 경우 이 속성은 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에서 변경: default_value 매개변수가 추가되었습니다.

함수와 클래스 정의

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

함수 정의.

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

  • argsarguments 노드입니다.

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

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

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

  • type_params is a list of type parameters.

type_comment

type_comment는 형 어노테이션이 주석으로 포함된 선택적 문자열입니다.

버전 3.12에서 변경: 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)

함수의 인자.

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

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

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

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

class ast.arg(arg, annotation, type_comment)

리스트의 단일 인수. arg 는 인수 이름의 원시 문자열이며, annotationName 노드와 같은 주석입니다.

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)

yield 또는 yield from 표현식입니다. 이러한 표현식은 반환되는 값이 사용되지 않는 경우 Expr 노드로 래핑해야 합니다.

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

globalnonlocal 문. 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는 명시적으로 지정된 베이스 클래스의 노드 리스트입니다.

  • keywordskeyword 노드의 목록이며, 주로 ‘métaclass’ 용도입니다. 다른 키워드는 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'),
                Name(id='base2')],
            keywords=[
                keyword(
                    arg='metaclass',
                    value=Name(id='meta'))],
            body=[
                Pass()],
            decorator_list=[
                Name(id='decorator1'),
                Name(id='decorator2')])])

버전 3.12에서 변경: type_params 가 추가되었습니다.

Async와 await

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

async def 함수 정의. FunctionDef와 같은 필드를 갖습니다.

버전 3.12에서 변경: 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(),
            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 컨텍스트 관리자. 이들은 각각 ForWith와 같은 필드를 갖습니다. AsyncFunctionDef의 본문에서만 유효합니다.

참고

ast.parse`에 의해 문자열이 구문 분석될 때, 반환된 트리에서 연산자 노드(:class:`ast.operator(), ast.unaryop, ast.cmpop, ast.boolopast.expr_context`의 하위 클래스)는 싱글톤이 됩니다. 하나에 대한 변경 사항은 동일한 값의 모든 다른 발생 위치에 반영됩니다 (예: :class:`ast.Add).

ast 헬퍼

노드 클래스 외에도, ast 모듈은 추상 구문 트리를 탐색하기 위해 다음 유틸리티 함수와 클래스를 정의합니다:

ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1, module=None)

소스를 AST 노드로 구문 분석합니다. FLAGS_VALUEoptimize <= 0 일 경우 ast.PyCF_ONLY_AST 와 같고, 그렇지 않은 경우 ast.PyCF_OPTIMIZED_AST 와 같습니다. 이는 compile(source, filename, mode, flags=FLAGS_VALUE, optimize=optimize, module=module) 와 동일합니다.

type_comments=True``를 지정하면, 파서는 :pep:`484`와 :pep:`526`에 명시된 타입 주석을 확인하고 반환하도록 수정됩니다. 이는 :func:`compile`에 전달되는 플래그에 :data:`ast.PyCF_TYPE_COMMENTS`를 추가하는 것과 같습니다. 이는 잘못 배치된 타입 주석에 대한 구문 오류를 보고합니다. 플래그가 없으면 타입 주석은 무시되며, 선택된 AST 노드에서 ``type_comment 필드는 항상 None``이 됩니다. 또한, ``# type: ignore 주석의 위치는 Module`의 ``type_ignores` 속성으로 반환됩니다 (그렇지 않으면 항상 빈 리스트입니다).

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

feature_version\을 튜플 (major, minor)\로 설정하면 해당 파이썬 버전의 문법을 사용하여 “최선 노력” 방식으로 구문 분석을 시도합니다. 예를 들어, feature_version=(3, 9)\를 설정하면 match 구문의 구문 분석을 허용하지 않으려고 시도합니다. 현재 major\는 3\과 같아야 합니다. 가장 낮은 지원 버전은 (3, 7)\입니다 (이것은 향후 파이썬 버전에서 증가할 수 있으며); 가장 높은 버전은 sys.version_info[0:2]\입니다. “최선 노력” 방식의 의미는 feature_version\에 해당하는 파이썬 버전에서 실행했을 때와 구문 분석(또는 구문 분석 성공)이 동일하다는 보장이 없다는 것입니다.

소스가 널 문자 (\0)를 포함하는 경우, :exc:`ValueError`가 발생합니다.

경고

성공적으로 소스 코드를 AST 객체로 파싱한다고 해서 제공된 소스 코드가 실행 가능한 유효한 파이썬 코드를 보장하는 것은 아니며, 컴파일 단계에서 추가적인 SyntaxError 예외가 발생할 수 있습니다. 예를 들어, 소스 return 42\는 return 문에 대한 유효한 AST 노드를 생성하지만, 단독으로 컴파일될 수 없습니다 (함수 노드 내부에 있어야 합니다).

특히, :func:`ast.parse`는 컴파일 단계에서 수행하는 스코핑 검사를 수행하지 않습니다.

경고

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

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

버전 3.13에서 변경: feature_version\에 대한 최소 지원 버전은 현재 (3, 7)\입니다. optimize 인수가 추가되었습니다.

Added in version 3.15: module 매개변수가 추가되었습니다.

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)

표현식 노드나 파이썬 리터럴 또는 컨테이너 디스플레이만을 포함하는 문자열을 평가합니다. 제공된 문자열이나 노드는 다음 파이썬 리터럴 구조로만 구성될 수 있습니다: 문자열, 바이트, 숫자, 튜플, 리스트, 딕셔너리, 세트, 부울, NoneEllipsis\입니다.

이것은 값을 직접 파싱할 필요 없이 파이썬 값을 포함하는 문자열을 평가하는 데 사용될 수 있습니다. 연산자나 인덱싱을 포함하는 등 임의로 복잡한 표현식을 평가하는 것은 불가능합니다.

이 함수는 과거에 ‘안전하다’고 문서화되었으나, 그 의미가 무엇인지 정의하지 않았습니다. 이는 오해의 소지가 있었습니다. 이 함수는 더 일반적인 :func:`eval`와 달리 파이썬 코드를 실행하지 않도록 특별히 설계되었습니다. 네임스페이스도 없고, 이름 조회 기능도 없으며, 호출할 수도 없습니다. 그러나 공격으로부터 자유롭지 않습니다: 상대적으로 작은 입력만으로도 메모리 고갈이나 C 스택 고갈을 유발하여 프로세스를 충돌시킬 수 있습니다. 또한 일부 입력에서는 과도한 CPU 소비로 인한 서비스 거부의 가능성도 있습니다. 따라서 신뢰할 수 없는 데이터에 이 함수를 호출하는 것은 권장되지 않습니다.

경고

파이썬의 AST 컴파일러에서 스택 깊이 제한으로 인해 파이썬 인터프리터가 충돌할 가능성이 있습니다.

잘못된 입력에 따라 ValueError, TypeError, SyntaxError, MemoryError 및 :exc:`RecursionError`를 발생시킬 수 있습니다.

버전 3.2에서 변경: 이제 바이트열과 집합 리터럴을 허용합니다.

버전 3.9에서 변경: 이제 'set()'으로 빈 집합을 만드는 것을 지원합니다.

버전 3.10에서 변경: 문자열 입력의 경우, 선행 공백과 탭이 이제 제거됩니다.

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)

node 을 생성한 source 의 소스 코드 세그먼트를 가져옵니다. 위치 정보 (lineno, end_lineno, col_offset, 또는 end_col_offset)가 누락된 경우 None 을 반환합니다.

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

Added in version 3.8.

ast.fix_missing_locations(node)

compile() 로 노드 트리를 컴파일할 때, 컴파일러는 지원하는 모든 노드에 대해 linenocol_offset 속성을 기대합니다. 이는 생성된 노드에 채우기에는 상당히 번거롭기 때문에, 이 헬퍼는 부모 노드의 값을 설정함으로써 해당 속성이 아직 설정되지 않은 곳에 재귀적으로 이 속성들을 추가합니다. node 에서 시작하여 재귀적으로 작동합니다.

ast.increment_lineno(node, n=1)

node에서 시작하는 트리에서 각 노드의 줄 번호와 끝 줄 번호를 n만큼 증가시킵니다. 파일의 다른 위치로 “코드를 이동”하는 데 유용합니다.

ast.copy_location(new_node, old_node)

가능한 경우 old_node 에서 new_node 로 소스 위치 (lineno, col_offset, end_lineno, 및 end_col_offset)를 복사하고 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)

모든 상수 노드를 처리합니다.

탐색 중에 노드에 변경 사항을 적용하려면 NodeVisitor를 사용하지 마십시오. 이를 위해 수정을 허락하는 특수한 방문자(NodeTransformer)가 있습니다.

버전 3.8에서 폐지되었고, 버전 3.14에서 제거됩니다: visit_Num(), visit_Str(), visit_Bytes(), visit_NameConstant()visit_Ellipsis() 메서드는 Python 3.14+에서 호출되지 않을 것입니다. 모든 상수 노드를 처리하려면 대신 visit_Constant() 메서드를 추가하십시오.

class ast.NodeTransformer

추상 구문 트리를 걷고 노드 수정을 허락하는 NodeVisitor 서브 클래스.

NodeTransformer는 AST를 걷고 방문자 메서드의 반환 값을 사용하여 이전 노드를 바꾸거나 제거합니다. 방문자 메서드의 반환 값이 None이면, 노드가 그 위치에서 제거되고, 그렇지 않으면 반환 값으로 치환됩니다. 반환 값은 원래 노드일 수 있으며, 이때는 치환이 일어나지 않습니다.

다음은 모든 이름 조회(foo)를 data['foo']로 다시 쓰는 변환기 예제입니다:

class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return Subscript(
            value=Name(id='data'),
            slice=Constant(value=node.id),
            ctx=node.ctx
        )

작업 중인 노드가 자식 노드를 가지고 있다면, 자식 노드를 직접 변환하거나 먼저 노드에 대해 generic_visit() 메서드를 호출해야 함을 명심하십시오.

문장의 컬렉션의 일부인 노드의 경우 (모든 문장 노드에 적용됩니다), 방문자는 단일 노드가 아닌 노드 리스트를 반환 할 수도 있습니다.

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, *, color=False, indent=None, show_empty=False)

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

colorTrue 이면, 반환된 문자열이 ANSI 이스케이프 시퀀스를 사용하여 구문 강조 표시됩니다. False (기본값)이면, 색상이 있는 출력은 항상 비활성화됩니다.

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

show_empty 가 false(기본값)이면, 선택적 빈 리스트와 Load() 값은 출력에서 생략됩니다. 선택적 None 값은 항상 생략됩니다.

>>> 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에서 변경: show_empty 옵션을 추가했습니다.

버전 3.15에서 변경: 선택적 Load() 값은 기본적으로 생략됩니다.

버전 3.15에서 변경: color 매개변수를 추가했습니다.

ast.compare(a, b, /, *, compare_attributes=False)

두 개의 AST를 재귀적으로 비교합니다.

compare_attributes 는 AST 속성이 비교에 고려되는지 여부에 영향을 줍니다. compare_attributesFalse (기본값)인 경우, 속성은 무시됩니다. 그렇지 않은 경우, 모두 동일해야 합니다. 이 옵션은 AST가 구조적으로 동일하지만 공백이나 유사한 세부 사항에서 차이가 있는지 확인하는 데 유용합니다. 속성에는 줄 번호와 열 오프셋이 포함됩니다.

Added in version 3.14.

컴파일러 플래그들

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

ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

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

Added in version 3.8.

ast.PyCF_ONLY_AST

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

ast.PyCF_OPTIMIZED_AST

반환된 AST는 :func:`compile`의 optimize 인자나 :func:`ast.parse`에 따라 최적화됩니다.

Added in version 3.13.

ast.PyCF_TYPE_COMMENTS

PEP 484PEP 526 스타일 형 주석(# type: <type>, # type: ignore <stuff>)에 대한 지원을 활성화합니다.

Added in version 3.8.

명령 줄 사용법

Added in version 3.9.

버전 3.15에서 변경: 출력은 이제 기본적으로 구문에 의해 강조 표시됩니다. 이는 환경 변수를 사용하여 제어할 수 있습니다 .

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에서 노드 들여쓰기(스페이스 수).

--feature-version <version>

Python 버전은 3.x 형식입니다 (예: 3.10). 인터프리터의 현재 버전을 기본값으로 합니다.

Added in version 3.14.

-O <level>
--optimize <level>

파서의 최적화 수준입니다. 기본적으로 최적화는 수행되지 않습니다.

Added in version 3.14.

--show-empty

빈 리스트와 None 인 필드를 표시합니다. 기본적으로 빈 객체는 표시하지 않습니다.

Added in version 3.14.

infile이 지정되면 그 내용이 AST로 구문 분석되고 stdout에 덤프 됩니다. 그렇지 않으면, stdin에서 내용을 읽습니다.

더 보기

Green Tree Snakes, 파이썬 AST로 작업하는 것에 대한 자세한 내용이 있는 외부 문서 자원.

ASTTokens는 토큰의 위치와 토큰을 생성한 소스 코드의 텍스트로 파이썬 AST에 주석을 추가합니다. 이는 소스 코드 변환을 수행하는 도구에 유용합니다.

`leoAst.py <https://leo-editor.github.io/leo-editor/appendices.html#leoast-py>`_는 토큰 기반 뷰와 파싱 트리 기반 뷰를 양방향 링크를 삽입하여 통합합니다.

LibCST는 코드를 ast 트리처럼 보이고 모든 포매팅 세부 정보를 유지하는 구상 구문 트리(Concrete Syntax Tree)로 구문 분석합니다. 자동화된 리팩토링 (codemod) 응용 프로그램과 린터(linter)를 구축하는 데 유용합니다.

`Parso <https://parso.readthedocs.io>`_는 오류 복구 및 다양한 Python 버전(여러 Python 버전에서)에 대한 왕복 구문 분석을 지원하는 Python 파서입니다. Parso는 또한 Python 파일에서 여러 구문 오류를 나열할 수 있습니다.

분실물 보관소