"ast" --- Abstract syntax trees
*******************************

**소스 코드:** Lib/ast.py

======================================================================

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

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


Abstract grammar
================

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

   -- ASDL's 4 builtin types are:
   -- identifier, int, string, constant

   module Python
   {
       mod = Module(stmt* body, type_ignore* type_ignores)
           | Interactive(stmt* body)
           | Expression(expr body)
           | FunctionType(expr* argtypes, expr returns)

       stmt = FunctionDef(identifier name, arguments args,
                          stmt* body, expr* decorator_list, expr? returns,
                          string? type_comment, type_param* type_params)
             | AsyncFunctionDef(identifier name, arguments args,
                                stmt* body, expr* decorator_list, expr? returns,
                                string? type_comment, type_param* type_params)

             | ClassDef(identifier name,
                expr* bases,
                keyword* keywords,
                stmt* body,
                expr* decorator_list,
                type_param* type_params)
             | Return(expr? value)

             | Delete(expr* targets)
             | Assign(expr* targets, expr value, string? type_comment)
             | TypeAlias(expr name, type_param* type_params, expr value)
             | AugAssign(expr target, operator op, expr value)
             -- 'simple' indicates that we annotate simple name without parens
             | AnnAssign(expr target, expr annotation, expr? value, int simple)

             -- use 'orelse' because else is a keyword in target languages
             | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
             | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)
             | While(expr test, stmt* body, stmt* orelse)
             | If(expr test, stmt* body, stmt* orelse)
             | With(withitem* items, stmt* body, string? type_comment)
             | AsyncWith(withitem* items, stmt* body, string? type_comment)

             | Match(expr subject, match_case* cases)

             | Raise(expr? exc, expr? cause)
             | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
             | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
             | Assert(expr test, expr? msg)

             | Import(alias* names)
             | ImportFrom(identifier? module, alias* names, int? level)

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

             -- col_offset is the byte offset in the utf8 string the parser uses
             attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

             -- BoolOp() can use left & right?
       expr = BoolOp(boolop op, expr* values)
            | NamedExpr(expr target, expr value)
            | BinOp(expr left, operator op, expr right)
            | UnaryOp(unaryop op, expr operand)
            | Lambda(arguments args, expr body)
            | IfExp(expr test, expr body, expr orelse)
            | Dict(expr?* keys, expr* values)
            | Set(expr* elts)
            | ListComp(expr elt, comprehension* generators)
            | SetComp(expr elt, comprehension* generators)
            | DictComp(expr key, expr value, comprehension* generators)
            | GeneratorExp(expr elt, comprehension* generators)
            -- the grammar constrains where yield expressions can occur
            | Await(expr value)
            | Yield(expr? value)
            | YieldFrom(expr value)
            -- need sequences for compare to distinguish between
            -- x < 4 < 3 and (x < 4) < 3
            | Compare(expr left, cmpop* ops, expr* comparators)
            | Call(expr func, expr* args, keyword* keywords)
            | FormattedValue(expr value, int conversion, expr? format_spec)
            | Interpolation(expr value, constant str, int conversion, expr? format_spec)
            | JoinedStr(expr* values)
            | TemplateStr(expr* values)
            | Constant(constant value, string? kind)

            -- the following expression can appear in assignment context
            | Attribute(expr value, identifier attr, expr_context ctx)
            | Subscript(expr value, expr slice, expr_context ctx)
            | Starred(expr value, expr_context ctx)
            | Name(identifier id, expr_context ctx)
            | List(expr* elts, expr_context ctx)
            | Tuple(expr* elts, expr_context ctx)

            -- can appear only in Subscript
            | Slice(expr? lower, expr? upper, expr? step)

             -- col_offset is the byte offset in the utf8 string the parser uses
             attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

       expr_context = Load | Store | Del

       boolop = And | Or

       operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
                    | RShift | BitOr | BitXor | BitAnd | FloorDiv

       unaryop = Invert | Not | UAdd | USub

       cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn

       comprehension = (expr target, expr iter, expr* ifs, int is_async)

       excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
                       attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

       arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,
                    expr* kw_defaults, arg? kwarg, expr* defaults)

       arg = (identifier arg, expr? annotation, string? type_comment)
              attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

       -- keyword arguments supplied to call (NULL identifier for **kwargs)
       keyword = (identifier? arg, expr value)
                  attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

       -- import name with optional 'as' alias.
       alias = (identifier name, identifier? asname)
                attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)

       withitem = (expr context_expr, expr? optional_vars)

       match_case = (pattern pattern, expr? guard, stmt* body)

       pattern = MatchValue(expr value)
               | MatchSingleton(constant value)
               | MatchSequence(pattern* patterns)
               | MatchMapping(expr* keys, pattern* patterns, identifier? rest)
               | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)

               | MatchStar(identifier? name)
               -- The optional "rest" MatchMapping parameter handles capturing extra mapping keys

               | MatchAs(pattern? pattern, identifier? name)
               | MatchOr(pattern* patterns)

                attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)

       type_ignore = TypeIgnore(int lineno, string tag)

       type_param = TypeVar(identifier name, expr? bound, expr? default_value)
                  | ParamSpec(identifier name, expr? default_value)
                  | TypeVarTuple(identifier name, expr? default_value)
                  attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
   }


노드 클래스
===========

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.stmt"나 "ast.expr"). 또한, 우변의 생성자마다 하나의
   클래스가 정의되어 있습니다; 이 클래스는 좌변 트리의 클래스에서 상속
   됩니다. 예를 들어, "ast.BinOp"는 "ast.expr"에서 상속됩니다. 대안을
   갖는 생성 규칙(일명 "합")의 경우, 좌변 클래스는 추상입니다: 특정 생
   성자 노드의 인스턴스만 만들어집니다.

   _fields

      Each concrete class has an attribute "_fields" which gives the
      names of all child nodes.

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

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

   _field_types

      The "_field_types" attribute on each concrete class is a
      dictionary mapping field names (as also listed in "_fields") to
      their types.

         >>> ast.TypeVar._field_types
         {'name': <class 'str'>, 'bound': ast.expr | None, 'default_value': ast.expr | None}

      Added in version 3.13.

   lineno
   col_offset
   end_lineno
   end_col_offset

      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(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
                         lineno=0, col_offset=0)

   If a field that is optional in the grammar is omitted from the
   constructor, it defaults to "None". If a list field is omitted, it
   defaults to the empty list. If a field of type "ast.expr_context"
   is omitted, it defaults to "Load()". If any other field is omitted,
   a "DeprecationWarning" is raised and the AST node will not have
   this field. In Python 3.15, this condition will raise an error.

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

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

버전 3.14에서 변경: The "__repr__()" output of "AST" nodes includes
the values of the node fields.

버전 3.8부터 폐지됨: Old classes "ast.Num", "ast.Str", "ast.Bytes",
"ast.NameConstant" and "ast.Ellipsis" are still available, but they
will be removed in future Python releases.  In the meantime,
instantiating them will return an instance of a different class.

버전 3.9부터 폐지됨: Old classes "ast.Index" and "ast.ExtSlice" are
still available, but they will be removed in future Python releases.
In the meantime, instantiating them will return an instance of a
different class.

Deprecated since version 3.13, will be removed in version 3.15:
Previous versions of Python allowed the creation of AST nodes that
were missing required fields. Similarly, AST node constructors allowed
arbitrary keyword arguments that were set as attributes of the AST
node, even if they did not match any of the fields of the AST node.
This behavior is deprecated and will be removed in Python 3.15.

참고:

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


Root nodes
----------

class ast.Module(body, type_ignores)

   A Python module, as with file input. Node type generated by
   "ast.parse()" in the default ""exec"" *mode*.

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

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

   Added in version 3.8.


리터럴
------

class ast.Constant(value)

   A constant value. The "value" attribute of the "Constant" literal
   contains the Python object it represents. The values represented
   can be instances of "str", "bytes", "int", "float", "complex", and
   "bool", and the constants "None" and "Ellipsis".

      >>> 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: 포매팅 없음

     * 97 ("ord('a')"): "!a" "ASCII" formatting

     * 114 ("ord('r')"): "!r" "repr()" formatting

     * 115 ("ord('s')"): "!s" "string" formatting

   * "format_spec"은 값의 포매팅을 나타내는 "JoinedStr" 노드이거나, 표
     맷이 지정되지 않았으면 "None"입니다. "conversion"과 "format_spec"
     을 동시에 설정할 수 있습니다.

class ast.JoinedStr(values)

   일련의 "FormattedValue"와 "Constant" 노드로 구성된 f-문자열.

      >>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode='eval'), indent=4))
      Expression(
          body=JoinedStr(
              values=[
                  Constant(value='sin('),
                  FormattedValue(
                      value=Name(id='a', ctx=Load()),
                      conversion=-1),
                  Constant(value=') is '),
                  FormattedValue(
                      value=Call(
                          func=Name(id='sin', ctx=Load()),
                          args=[
                              Name(id='a', ctx=Load())]),
                      conversion=-1,
                      format_spec=JoinedStr(
                          values=[
                              Constant(value='.3')]))]))

class ast.TemplateStr(values, /)

   Added in version 3.14.

   Node representing a template string literal, comprising a series of
   "Interpolation" and "Constant" nodes. These nodes may be any order,
   and do not need to be interleaved.

      >>> expr = ast.parse('t"{name} finished {place:ordinal}"', mode='eval')
      >>> print(ast.dump(expr, indent=4))
      Expression(
          body=TemplateStr(
              values=[
                  Interpolation(
                      value=Name(id='name', ctx=Load()),
                      str='name',
                      conversion=-1),
                  Constant(value=' finished '),
                  Interpolation(
                      value=Name(id='place', ctx=Load()),
                      str='place',
                      conversion=-1,
                      format_spec=JoinedStr(
                          values=[
                              Constant(value='ordinal')]))]))

class ast.Interpolation(value, str, conversion, format_spec=None)

   Added in version 3.14.

   Node representing a single interpolation field in a template string
   literal.

   * "value" is any expression node (such as a literal, a variable, or
     a function call). This has the same meaning as
     "FormattedValue.value".

   * "str" is a constant containing the text of the interpolation
     expression.

     If "str" is set to "None", then "value" is used to generate code
     when calling "ast.unparse()". This no longer guarantees that the
     generated code is identical to the original and is intended for
     code generation.

   * "conversion"은 정수입니다:

     * -1: no conversion

     * 97 ("ord('a')"): "!a" "ASCII" conversion

     * 114 ("ord('r')"): "!r" "repr()" conversion

     * 115 ("ord('s')"): "!s" "string" conversion

     This has the same meaning as "FormattedValue.conversion".

   * "format_spec" is a "JoinedStr" node representing the formatting
     of the value, or "None" if no format was specified. Both
     "conversion" and "format_spec" can be set at the same time. This
     has the same meaning as "FormattedValue.format_spec".

class ast.List(elts, ctx)
class ast.Tuple(elts, ctx)

   리스트나 튜플. "elts"는 요소를 나타내는 노드의 리스트를 보유합니다.
   "ctx"는 컨테이너가 대입 대상이면 (가령 "(x,y)=something") "Store"이
   고, 그렇지 않으면 "Load"입니다.

      >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
      Expression(
          body=List(
              elts=[
                  Constant(value=1),
                  Constant(value=2),
                  Constant(value=3)],
              ctx=Load()))
      >>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
      Expression(
          body=Tuple(
              elts=[
                  Constant(value=1),
                  Constant(value=2),
                  Constant(value=3)],
              ctx=Load()))

class ast.Set(elts)

   집합. "elts"는 집합의 요소를 나타내는 노드의 리스트를 보유합니다.

      >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
      Expression(
          body=Set(
              elts=[
                  Constant(value=1),
                  Constant(value=2),
                  Constant(value=3)]))

class ast.Dict(keys, values)

   딕셔너리. "keys"와 "values"는 각각 키와 값을 나타내는 노드의 리스트
   를 일치하는 순서대로 ("dictionary.keys()"와 "dictionary.values()"를
   호출할 때 반환되는 순서) 보유합니다.

   딕셔너리 리터럴을 사용하여 딕셔너리 언 패킹을 수행할 때 확장될 표현
   식은 "values" 리스트로 가고, "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()))])

      >>> print(ast.dump(ast.parse('a = 1'), indent=4))
      Module(
          body=[
              Assign(
                  targets=[
                      Name(id='a', ctx=Store())],
                  value=Constant(value=1))])

      >>> print(ast.dump(ast.parse('del a'), indent=4))
      Module(
          body=[
              Delete(
                  targets=[
                      Name(id='a', ctx=Del())])])

class ast.Starred(value, ctx)

   "*var" 변수 참조. "value"는 변수(일반적으로 "Name" 노드)를 보유합니
   다. 이 형은 "*args"로 "Call" 노드를 빌드할 때 사용해야 합니다.

      >>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
      Module(
          body=[
              Assign(
                  targets=[
                      Tuple(
                          elts=[
                              Name(id='a', ctx=Store()),
                              Starred(
                                  value=Name(id='b', ctx=Store()),
                                  ctx=Store())],
                          ctx=Store())],
                  value=Name(id='it', ctx=Load()))])


표현식
------

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

class ast.UnaryOp(op, operand)

   단항 연산. "op"는 연산자이고, "operand"는 임의의 표현식 노드입니다.

class ast.UAdd
class ast.USub
class ast.Not
class ast.Invert

   단항 연산자 토큰. "Not"은 "not" 키워드이고, "Invert"는 "~" 연산자입
   니다.

      >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
      Expression(
          body=UnaryOp(
              op=Not(),
              operand=Name(id='x', ctx=Load())))

class ast.BinOp(left, op, right)

   이항 연산 (더하기나 나누기 같은). "op"는 연산자이고, "left"와
   "right"는 임의의 표현식 노드입니다.

      >>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
      Expression(
          body=BinOp(
              left=Name(id='x', ctx=Load()),
              op=Add(),
              right=Name(id='y', ctx=Load())))

class ast.Add
class ast.Sub
class ast.Mult
class ast.Div
class ast.FloorDiv
class ast.Mod
class ast.Pow
class ast.LShift
class ast.RShift
class ast.BitOr
class ast.BitXor
class ast.BitAnd
class ast.MatMult

   이항 연산자 토큰.

class ast.BoolOp(op, values)

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

   여기에는 "UnaryOp"인 "not"이 포함되지 않습니다.

      >>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
      Expression(
          body=BoolOp(
              op=Or(),
              values=[
                  Name(id='x', ctx=Load()),
                  Name(id='y', ctx=Load())]))

class ast.And
class ast.Or

   불리언 연산자 토큰.

class ast.Compare(left, ops, comparators)

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

   The "args" and "keywords" arguments are optional and default to
   empty lists.

      >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
      Expression(
          body=Call(
              func=Name(id='func', 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" 노드와 달리, 이 경우에는 "target"과 "value"는 모두
   단일 노드여야 합니다.

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

   Added in version 3.8.


서브스크립팅
~~~~~~~~~~~~

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:upper"나 "lower:upper:step" 형식).
   "Subscript"의 *slice* 필드 내에서만 직접 또는 "Tuple"의 요소로 등장
   할 수 있습니다.

      >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
      Expression(
          body=Subscript(
              value=Name(id='l', ctx=Load()),
              slice=Slice(
                  lower=Constant(value=1),
                  upper=Constant(value=2)),
              ctx=Load()))


컴프리헨션
~~~~~~~~~~

class ast.ListComp(elt, generators)
class ast.SetComp(elt, generators)
class ast.GeneratorExp(elt, generators)
class ast.DictComp(key, value, generators)

   리스트와 집합 컴프리헨션, 제너레이터 표현식 및 딕셔너리 컴프리헨션.
   "elt"(또는 "key"와 "value")는 항목마다 평가될 부분을 나타내는 단일
   노드입니다.

   "generators"는 "comprehension" 노드의 리스트입니다.

      >>> 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()),
                      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()),
                      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()),
                      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())]),
              generators=[
                  comprehension(
                      target=Name(id='line', ctx=Store()),
                      iter=Name(id='file', ctx=Load()),
                      is_async=0),
                  comprehension(
                      target=Name(id='c', ctx=Store()),
                      iter=Name(id='line', ctx=Load()),
                      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()),
                      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))])

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

class ast.AnnAssign(target, annotation, value, simple)

   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.

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

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

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

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

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

class ast.AugAssign(target, op, value)

   증분 대입, 가령 "a += 1". 다음 예에서, "target"은 "x"("Store" 컨텍
   스트로)를 위한 "Name" 노드이고, "op"는 "Add"이며, "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))])

class ast.Raise(exc, cause)

   "raise" 문. "exc"는 발생시킬 예외 객체로 일반적으로 "Call"이나
   "Name"이거나, 독립 "raise"의 경우 "None"입니다. "cause"는 "raise x
   from y"에서 "y"에 해당하는 선택적 부분입니다.

      >>> print(ast.dump(ast.parse('raise x from y'), indent=4))
      Module(
          body=[
              Raise(
                  exc=Name(id='x', ctx=Load()),
                  cause=Name(id='y', ctx=Load()))])

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

class ast.Delete(targets)

   "del" 문을 나타냅니다. "targets"는 "Name", "Attribute" 또는
   "Subscript" 같은 노드들의 리스트입니다.

      >>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
      Module(
          body=[
              Delete(
                  targets=[
                      Name(id='x', ctx=Del()),
                      Name(id='y', ctx=Del()),
                      Name(id='z', ctx=Del())])])

class ast.Pass

   "pass" 문.

      >>> print(ast.dump(ast.parse('pass'), indent=4))
      Module(
          body=[
              Pass()])

class ast.TypeAlias(name, type_params, value)

   A type alias created through the "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', ctx=Load()))])

   Added in version 3.12.

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


임포트
~~~~~~

class ast.Import(names)

   import 문. "names"는 "alias" 노드의 리스트입니다.

      >>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
      Module(
          body=[
              Import(
                  names=[
                      alias(name='x'),
                      alias(name='y'),
                      alias(name='z')])])

class ast.ImportFrom(module, names, level)

   "from x import y"를 나타냅니다. "module"은  선행 점이 없는 'from'
   이름의 원시 문자열이며, "from . import foo"와 같은 문장의 경우
   "None"입니다. "level"은 상대 임포트 수준을 보유하는 정수입니다 (0은
   절대 임포트를 의미합니다).

      >>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
      Module(
          body=[
              ImportFrom(
                  module='y',
                  names=[
                      alias(name='x'),
                      alias(name='y'),
                      alias(name='z')],
                  level=0)])

class ast.alias(name, asname)

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

      >>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
      Module(
          body=[
              ImportFrom(
                  module='foo.bar',
                  names=[
                      alias(name='a', asname='b'),
                      alias(name='c')],
                  level=2)])


제어 흐름
---------

참고:

  "else"와 같은 선택적 절은 존재하지 않으면 빈 목록으로 저장됩니다.

class ast.If(test, body, orelse)

   "if" 문. "test"는 ("Compare" 노드와 같은) 단일 노드를 보유합니다.
   "body"와 "orelse"는 각각 노드 리스트를 보유합니다.

   "elif" 절은 AST에서 특별한 표현이 없지만, 앞의 "orelse" 섹션 안에서
   추가 "If" 노드로 나타납니다.

      >>> print(ast.dump(ast.parse("""
      ... if x:
      ...    ...
      ... elif y:
      ...    ...
      ... else:
      ...    ...
      ... """), indent=4))
      Module(
          body=[
              If(
                  test=Name(id='x', 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))])])])

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

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

class ast.Break
class ast.Continue

   "break"와 "continue" 문.

      >>> print(ast.dump(ast.parse("""\
      ... for a in b:
      ...     if a > 5:
      ...         break
      ...     else:
      ...         continue
      ...
      ... """), indent=4))
      Module(
          body=[
              For(
                  target=Name(id='a', ctx=Store()),
                  iter=Name(id='b', ctx=Load()),
                  body=[
                      If(
                          test=Compare(
                              left=Name(id='a', ctx=Load()),
                              ops=[
                                  Gt()],
                              comparators=[
                                  Constant(value=5)]),
                          body=[
                              Break()],
                          orelse=[
                              Continue()])])])

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

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

   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', ctx=Load()),
                              op=Add(),
                              right=Constant(value=1)))],
                  handlers=[
                      ExceptHandler(
                          type=Name(id='TypeError', ctx=Load()),
                          body=[
                              Pass()])])])

class ast.With(items, body, type_comment)

   "with" 블록. "items"는 컨텍스트 관리자를 나타내는 "withitem" 노드의
   리스트이며, "body"는 컨텍스트 내에서 들여쓰기 된 블록입니다.

   type_comment

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

class ast.withitem(context_expr, optional_vars)

   "with" 블록의 단일 컨텍스트 관리자. "context_expr"은 컨텍스트 관리
   자이며, 종종 "Call" 노드입니다. "optional_vars"는 "as foo" 부분의
   경우 "Name", "Tuple" 또는 "List"이거나, 사용하지 않으면 "None"입니
   다.

      >>> print(ast.dump(ast.parse("""\
      ... with a as b, c as d:
      ...    something(b, d)
      ... """), indent=4))
      Module(
          body=[
              With(
                  items=[
                      withitem(
                          context_expr=Name(id='a', 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())]))])])


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.

   Added in version 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())),
                          body=[
                              Expr(
                                  value=Constant(value=Ellipsis))])])])

   Added in version 3.10.

class ast.MatchValue(value)

   A match literal or value pattern that compares by equality. "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))])])])

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

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

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

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

   Added in version 3.10.

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

   A match class pattern. "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))]),
                          body=[
                              Expr(
                                  value=Constant(value=Ellipsis))]),
                      match_case(
                          pattern=MatchClass(
                              cls=Name(id='Point3D', ctx=Load()),
                              kwd_attrs=[
                                  'x',
                                  'y',
                                  'z'],
                              kwd_patterns=[
                                  MatchValue(
                                      value=Constant(value=0)),
                                  MatchValue(
                                      value=Constant(value=0)),
                                  MatchValue(
                                      value=Constant(value=0))]),
                          body=[
                              Expr(
                                  value=Constant(value=Ellipsis))])])])

   Added in version 3.10.

class ast.MatchAs(pattern, name)

   A match "as-pattern", capture pattern or wildcard pattern.
   "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))])])])

   Added in version 3.10.

class ast.MatchOr(patterns)

   A match "or-pattern". An or-pattern matches each of its subpatterns
   in turn to the subject, until one succeeds. The or-pattern is then
   deemed to succeed. If none of the subpatterns succeed the or-
   pattern fails. The "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))])])])

   Added in version 3.10.


Type annotations
----------------

class ast.TypeIgnore(lineno, tag)

   A "# type: ignore" comment located at *lineno*. *tag* is the
   optional tag specified by the form "# type: ignore <tag>".

      >>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), indent=4))
      Module(
          body=[
              Assign(
                  targets=[
                      Name(id='x', ctx=Store())],
                  value=Constant(value=1))],
          type_ignores=[
              TypeIgnore(lineno=1, tag='')])
      >>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', type_comments=True), indent=4))
      Module(
          body=[
              AnnAssign(
                  target=Name(id='x', ctx=Store()),
                  annotation=Name(id='bool', ctx=Load()),
                  value=Constant(value=1),
                  simple=1)],
          type_ignores=[
              TypeIgnore(lineno=1, tag='[assignment]')])

   참고:

     "TypeIgnore" nodes are not generated when the *type_comments*
     parameter is set to "False" (default).  See "ast.parse()" for
     more details.

   Added in version 3.8.


Type parameters
---------------

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

class ast.TypeVar(name, bound, default_value)

   A "typing.TypeVar". "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. "default_value" is the default value; if the "TypeVar" has
   no default, this attribute will be set to "None".

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

   Added in version 3.12.

   버전 3.13에서 변경: Added the *default_value* parameter.

class ast.ParamSpec(name, default_value)

   A "typing.ParamSpec". "name" is the name of the parameter
   specification. "default_value" is the default value; if the
   "ParamSpec" has no default, this attribute will be set to "None".

      >>> print(ast.dump(ast.parse("type Alias[**P = [int, str]] = Callable[P, int]"), indent=4))
      Module(
          body=[
              TypeAlias(
                  name=Name(id='Alias', ctx=Store()),
                  type_params=[
                      ParamSpec(
                          name='P',
                          default_value=List(
                              elts=[
                                  Name(id='int', ctx=Load()),
                                  Name(id='str', ctx=Load())],
                              ctx=Load()))],
                  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()))])

   Added in version 3.12.

   버전 3.13에서 변경: Added the *default_value* parameter.

class ast.TypeVarTuple(name, default_value)

   A "typing.TypeVarTuple". "name" is the name of the type variable
   tuple. "default_value" is the default value; if the "TypeVarTuple"
   has no default, this attribute will be set to "None".

      >>> print(ast.dump(ast.parse("type Alias[*Ts = ()] = tuple[*Ts]"), indent=4))
      Module(
          body=[
              TypeAlias(
                  name=Name(id='Alias', ctx=Store()),
                  type_params=[
                      TypeVarTuple(
                          name='Ts',
                          default_value=Tuple(ctx=Load()))],
                  value=Subscript(
                      value=Name(id='tuple', ctx=Load()),
                      slice=Tuple(
                          elts=[
                              Starred(
                                  value=Name(id='Ts', ctx=Load()),
                                  ctx=Load())],
                          ctx=Load()),
                      ctx=Load()))])

   Added in version 3.12.

   버전 3.13에서 변경: Added the *default_value* parameter.


함수와 클래스 정의
------------------

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

   함수 정의.

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

   * "args" 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(
                          args=[
                              arg(arg='x'),
                              arg(arg='y')]),
                      body=Constant(value=Ellipsis)))])

class ast.arguments(posonlyargs, args, vararg, kwonlyargs, kw_defaults, kwarg, defaults)

   함수의 인자.

   * "posonlyargs", "args" 및 "kwonlyargs"는 "arg" 노드의 리스트입니다
     .

   * "vararg"와 "kwarg"는 "*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(
                      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'))])

class ast.Return(value)

   "return" 문.

      >>> print(ast.dump(ast.parse('return 4'), indent=4))
      Module(
          body=[
              Return(
                  value=Constant(value=4))])

class ast.Yield(value)
class ast.YieldFrom(value)

   A "yield" or "yield from" expression. Because these are
   expressions, they must be wrapped in an "Expr" node if the value
   sent back is not used.

      >>> print(ast.dump(ast.parse('yield x'), indent=4))
      Module(
          body=[
              Expr(
                  value=Yield(
                      value=Name(id='x', ctx=Load())))])

      >>> print(ast.dump(ast.parse('yield from x'), indent=4))
      Module(
          body=[
              Expr(
                  value=YieldFrom(
                      value=Name(id='x', ctx=Load())))])

class ast.Global(names)
class ast.Nonlocal(names)

   "global"과 "nonlocal" 문. "names"는 원시 문자열 리스트입니다.

      >>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
      Module(
          body=[
              Global(
                  names=[
                      'x',
                      'y',
                      'z'])])

      >>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
      Module(
          body=[
              Nonlocal(
                  names=[
                      'x',
                      'y',
                      'z'])])

class ast.ClassDef(name, bases, keywords, body, decorator_list, type_params)

   클래스 정의.

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

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

   * "keywords" is a list of "keyword" nodes, principally for
     'metaclass'. Other keywords will be passed to the metaclass, as
     per **PEP 3115**.

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

   * "decorator_list"는 "FunctionDef"에서와 같이 노드 리스트입니다.

   * "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())])])

   버전 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(),
               body=[
                   Expr(
                       value=Await(
                           value=Call(
                               func=Name(id='other_func', ctx=Load()))))])])

class ast.AsyncFor(target, iter, body, orelse, type_comment)
class ast.AsyncWith(items, body, type_comment)

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

참고:

  When a string is parsed by "ast.parse()", operator nodes (subclasses
  of "ast.operator", "ast.unaryop", "ast.cmpop", "ast.boolop" and
  "ast.expr_context") on the returned tree will be singletons. Changes
  to one will be reflected in all other occurrences of the same value
  (for example, "ast.Add").


"ast" helpers
=============

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

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

   Parse the source into an AST node.  Equivalent to "compile(source,
   filename, mode, flags=FLAGS_VALUE, optimize=optimize)", where
   "FLAGS_VALUE" is "ast.PyCF_ONLY_AST" if "optimize <= 0" and
   "ast.PyCF_OPTIMIZED_AST" otherwise.

   If "type_comments=True" is given, the parser is modified to check
   and return type comments as specified by **PEP 484** and **PEP
   526**. This is equivalent to adding "ast.PyCF_TYPE_COMMENTS" to the
   flags passed to "compile()".  This will report syntax errors for
   misplaced type comments.  Without this flag, type comments will be
   ignored, and the "type_comment" field on selected AST nodes will
   always be "None".  In addition, the locations of "# type: ignore"
   comments will be returned as the "type_ignores" attribute of
   "Module" (otherwise it is always an empty list).

   또한, "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, 7)" (and this
   may increase in future Python versions); the highest is
   "sys.version_info[0:2]". "Best-effort" attempt means there is no
   guarantee that the parse (or success of the parse) is the same as
   when run on the Python version corresponding to "feature_version".

   If source contains a null character ("\0"), "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"추가했습니다.

   버전 3.13에서 변경: The minimum supported version for
   "feature_version" is now "(3, 7)". The "optimize" argument was
   added.

ast.unparse(ast_obj)

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

   경고:

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

   경고:

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

   Added in version 3.9.

ast.literal_eval(node_or_string)

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

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

   Added in version 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, show_empty=False)

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

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

   If *show_empty* is false (the default), optional empty lists will
   be omitted from the output. Optional "None" values are always
   omitted.

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

   버전 3.13에서 변경: Added the *show_empty* option.

      >>> print(ast.dump(ast.parse("""\
      ... async def f():
      ...     await other_func()
      ... """), indent=4, show_empty=True))
      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=[])


Compiler flags
==============

프로그램 컴파일에 대한 효과를 변경하기 위해 다음 플래그를 "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

   The returned AST is optimized according to the *optimize* argument
   in "compile()" or "ast.parse()".

   Added in version 3.13.

ast.PyCF_TYPE_COMMENTS

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

   Added in version 3.8.

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

   Recursively compares two ASTs.

   *compare_attributes* affects whether AST attributes are considered
   in the comparison. If *compare_attributes* is "False" (default),
   then attributes are ignored. Otherwise they must all be equal. This
   option is useful to check whether the ASTs are structurally equal
   but differ in whitespace or similar details. Attributes include
   line numbers and column offsets.

   Added in version 3.14.


Command-line usage
==================

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

--feature-version <version>

   Python version in the format 3.x (for example, 3.10). Defaults to
   the current version of the interpreter.

   Added in version 3.14.

-O <level>
--optimize <level>

   Optimization level for parser. Defaults to no optimization.

   Added in version 3.14.

--show-empty

   Show empty lists and fields that are "None". Defaults to not
   showing empty objects.

   Added in version 3.14.

"infile"이 지정되면 그 내용이 AST로 구문 분석되고 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.
