"ast" --- 추상 구문 트리
************************

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

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

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

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


추상 문법
=========

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

       expr_context = Load | Store | Del

       boolop = And | Or

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

       unaryop = Invert | Not | UAdd | USub

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

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

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

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

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

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

       -- import name with optional 'as' alias.
       alias = (identifier name, identifier? asname)

       withitem = (expr context_expr, expr? optional_vars)

       type_ignore = TypeIgnore(int lineno, string tag)
   }


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

class ast.AST

   이것은 모든 AST 노드 클래스의 베이스입니다. 실제 노드 클래스는
   "Parser/Python.asdl" 파일에서 파생되며, 이 파일의 내용은 아래에서
   볼 수 있습니다. "_ast" C 모듈에 정의되어 있으며 "ast"로 다시 내보내
   집니다.

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

   _fields

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

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

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

   lineno
   col_offset
   end_lineno
   end_col_offset

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

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

   "ast.T" 클래스의 생성자는 다음과 같이 인자를 구문 분석합니다:

   * 위치 인자가 있으면, "T._fields"에 있는 항목 수만큼 있어야 합니다;
     이러한 이름의 어트리뷰트로 대입될 것입니다.

   * 키워드 인자가 있으면, 같은 이름의 어트리뷰트를 지정된 값으로 설정
     합니다.

   예를 들어, "ast.UnaryOp" 노드를 만들고 채우려면, 다음과 같이 할 수
   있습니다

      node = ast.UnaryOp()
      node.op = ast.USub()
      node.operand = ast.Constant()
      node.operand.value = 5
      node.operand.lineno = 0
      node.operand.col_offset = 0
      node.lineno = 0
      node.col_offset = 0

   또는 더 간결하게

      node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
                         lineno=0, col_offset=0)

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

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

버전 3.8부터 폐지: 이전 클래스 "ast.Num", "ast.Str", "ast.Bytes",
"ast.NameConstant" 및 "ast.Ellipsis"는 여전히 사용할 수 있지만, 향후
파이썬 릴리스에서 제거될 예정입니다. 그동안, 이들을 인스턴스 화하면 다
른 클래스의 인스턴스가 반환됩니다.

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

참고:

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


리터럴
------

class ast.Constant(value)

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

      >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
      Expression(
          body=Constant(value=123))

class ast.FormattedValue(value, conversion, format_spec)

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

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

   * "conversion"은 정수입니다:

     * -1: 포매팅 없음

     * 115: "!s" 문자열 포매팅

     * 114: "!r" repr 포매팅

     * 97: "!a" ascii 포매팅

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

class ast.JoinedStr(values)

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

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

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

   리스트나 튜플. "elts"는 요소를 나타내는 노드의 리스트를 보유합니다.
   "ctx"는 컨테이너가 대입 대상이면 (가령 "(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()))],
          type_ignores=[])

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

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

class ast.Starred(value, ctx)

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

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


표현식
------

class ast.Expr(value)

   표현식(가령 함수 호출)이 반환 값이 사용되거나 저장되지 않은 자신만
   의 문장으로 나타나면, 이 컨테이너에 래핑 됩니다. "value"는 이 섹션
   의 다른 노드인 "Constant", "Name", "Lambda", "Yield" 또는
   "YieldFrom" 노드 중 하나를 보유합니다.

      >>> print(ast.dump(ast.parse('-a'), indent=4))
      Module(
          body=[
              Expr(
                  value=UnaryOp(
                      op=USub(),
                      operand=Name(id='a', ctx=Load())))],
          type_ignores=[])

class ast.UnaryOp(op, operand)

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

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

   단항 연산자 토큰. "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, starargs, kwargs)

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

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

   * "keywords"는 키워드로 전달된 인자를 나타내는 "keyword" 객체의 리
     스트를 보유합니다.

   "Call" 노드를 만들 때, "args"와 "keywords"는 필수이지만, 비어있는
   리스트일 수 있습니다. "starargs"와 "kwargs"는 선택적입니다.

      >>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
      Expression(
          body=Call(
              func=Name(id='func', ctx=Load()),
              args=[
                  Name(id='a', ctx=Load()),
                  Starred(
                      value=Name(id='d', ctx=Load()),
                      ctx=Load())],
              keywords=[
                  keyword(
                      arg='b',
                      value=Name(id='c', ctx=Load())),
                  keyword(
                      value=Name(id='e', ctx=Load()))]))

class ast.keyword(arg, value)

   함수 호출이나 클래스 정의에 대한 키워드 인자. "arg"는 매개 변수 이
   름의 원시 문자열이고, "value"는 전달할 노드입니다.

class ast.IfExp(test, body, orelse)

   "a if b else c"와 같은 표현식. 각 필드는 단일 노드를 보유해서, 다음
   예에서, 세 개 모두 "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)))


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

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()),
                      ifs=[],
                      is_async=0)]))
      >>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
      Expression(
          body=DictComp(
              key=Name(id='x', ctx=Load()),
              value=BinOp(
                  left=Name(id='x', ctx=Load()),
                  op=Pow(),
                  right=Constant(value=2)),
              generators=[
                  comprehension(
                      target=Name(id='x', ctx=Store()),
                      iter=Name(id='numbers', ctx=Load()),
                      ifs=[],
                      is_async=0)]))
      >>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
      Expression(
          body=SetComp(
              elt=Name(id='x', ctx=Load()),
              generators=[
                  comprehension(
                      target=Name(id='x', ctx=Store()),
                      iter=Name(id='numbers', ctx=Load()),
                      ifs=[],
                      is_async=0)]))

class ast.comprehension(target, iter, ifs, is_async)

   컴프리헨션에서 하나의 "for" 절. "target"은 각 요소(보통 "Name"이나
   "Tuple" 노드)에 사용할 참조입니다. "iter"는 이터레이트 할 객체입니
   다. "ifs"는 테스트 표현식의 리스트입니다: 각 "for" 절은 여러 "ifs"
   를 가질 수 있습니다.

   "is_async"는 컴프리헨션이 비동기임을 나타냅니다 ("for" 대신 "async
   for"를 사용합니다). 값은 정수(0이나 1)입니다.

      >>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
      ...                indent=4)) # Multiple comprehensions in one.
      Expression(
          body=ListComp(
              elt=Call(
                  func=Name(id='ord', ctx=Load()),
                  args=[
                      Name(id='c', ctx=Load())],
                  keywords=[]),
              generators=[
                  comprehension(
                      target=Name(id='line', ctx=Store()),
                      iter=Name(id='file', ctx=Load()),
                      ifs=[],
                      is_async=0),
                  comprehension(
                      target=Name(id='c', ctx=Store()),
                      iter=Name(id='line', ctx=Load()),
                      ifs=[],
                      is_async=0)]))

      >>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),
      ...                indent=4)) # generator comprehension
      Expression(
          body=GeneratorExp(
              elt=BinOp(
                  left=Name(id='n', ctx=Load()),
                  op=Pow(),
                  right=Constant(value=2)),
              generators=[
                  comprehension(
                      target=Name(id='n', ctx=Store()),
                      iter=Name(id='it', ctx=Load()),
                      ifs=[
                          Compare(
                              left=Name(id='n', ctx=Load()),
                              ops=[
                                  Gt()],
                              comparators=[
                                  Constant(value=5)]),
                          Compare(
                              left=Name(id='n', ctx=Load()),
                              ops=[
                                  Lt()],
                              comparators=[
                                  Constant(value=10)])],
                      is_async=0)]))

      >>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
      ...                indent=4)) # Async comprehension
      Expression(
          body=ListComp(
              elt=Name(id='i', ctx=Load()),
              generators=[
                  comprehension(
                      target=Name(id='i', ctx=Store()),
                      iter=Name(id='soc', ctx=Load()),
                      ifs=[],
                      is_async=1)]))


문장
----

class ast.Assign(targets, value, type_comment)

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

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

   type_comment

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

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

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

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

   형 주석이 있는 대입. "target"은 단일 노드이며 "Name", "Attribute"
   또는 "Subscript"일 수 있습니다. "annotation"은 "Constant"나 "Name"
   노드와 같은 어노테이션입니다. "value"는 단일 선택적 노드입니다.
   "simple"은 괄호 사이에 나타나지 않은 순수한 이름이며 표현식이 아닌
   "target"의 "Name" 노드에 대해 True로 설정된 불리언 정수입니다.

      >>> print(ast.dump(ast.parse('c: int'), indent=4))
      Module(
          body=[
              AnnAssign(
                  target=Name(id='c', ctx=Store()),
                  annotation=Name(id='int', ctx=Load()),
                  simple=1)],
          type_ignores=[])

      >>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
      Module(
          body=[
              AnnAssign(
                  target=Name(id='a', ctx=Store()),
                  annotation=Name(id='int', ctx=Load()),
                  value=Constant(value=1),
                  simple=0)],
          type_ignores=[])

      >>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
      Module(
          body=[
              AnnAssign(
                  target=Attribute(
                      value=Name(id='a', ctx=Load()),
                      attr='b',
                      ctx=Store()),
                  annotation=Name(id='int', ctx=Load()),
                  simple=0)],
          type_ignores=[])

      >>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
      Module(
          body=[
              AnnAssign(
                  target=Subscript(
                      value=Name(id='a', ctx=Load()),
                      slice=Constant(value=1),
                      ctx=Store()),
                  annotation=Name(id='int', ctx=Load()),
                  simple=0)],
          type_ignores=[])

class ast.AugAssign(target, op, value)

   증분 대입, 가령 "a += 1". 다음 예에서, "target"은 "x"("Store" 컨텍
   스트로)를 위한 "Name" 노드이고, "op"는 "Add"이며, "value"는 값이 1
   인 "Constant"입니다.

   "target" 어트리뷰트는 "Assign"의 대상과 달리 "Tuple"이나 "List" 클
   래스일 수 없습니다.

      >>> print(ast.dump(ast.parse('x += 2'), indent=4))
      Module(
          body=[
              AugAssign(
                  target=Name(id='x', ctx=Store()),
                  op=Add(),
                  value=Constant(value=2))],
          type_ignores=[])

class ast.Raise(exc, cause)

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

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

class ast.Assert(test, msg)

   어서션. "test"는 ("Compare" 노드와 같은) 조건을 보유합니다. "msg"는
   실패 메시지를 보유합니다.

      >>> print(ast.dump(ast.parse('assert x,y'), indent=4))
      Module(
          body=[
              Assert(
                  test=Name(id='x', ctx=Load()),
                  msg=Name(id='y', ctx=Load()))],
          type_ignores=[])

class ast.Delete(targets)

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

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

class ast.Pass

   "pass" 문.

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

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


임포트
~~~~~~

class ast.Import(names)

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

class ast.ImportFrom(module, names, level)

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

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

class ast.alias(name, asname)

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

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


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

참고:

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

class ast.If(test, body, orelse)

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

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

      >>> print(ast.dump(ast.parse("""
      ... if x:
      ...    ...
      ... elif y:
      ...    ...
      ... else:
      ...    ...
      ... """), indent=4))
      Module(
          body=[
              If(
                  test=Name(id='x', ctx=Load()),
                  body=[
                      Expr(
                          value=Constant(value=Ellipsis))],
                  orelse=[
                      If(
                          test=Name(id='y', ctx=Load()),
                          body=[
                              Expr(
                                  value=Constant(value=Ellipsis))],
                          orelse=[
                              Expr(
                                  value=Constant(value=Ellipsis))])])],
          type_ignores=[])

class ast.For(target, iter, body, orelse, type_comment)

   "for" 루프 "target"은 루프가 대입하는 변수를 단일 "Name", "Tuple"
   또는 "List" 노드로 보유합니다. "iter"는 루핑할 항목을 역시 단일 노
   드로 보유합니다. "body"와 "orelse"는 실행할 노드의 리스트를 포함합
   니다. 루프가 "break" 문을 통하지 않고 정상적으로 완료되면 "orelse"
   에 있는 노드가 실행됩니다.

   type_comment

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

      >>> print(ast.dump(ast.parse("""
      ... for x in y:
      ...     ...
      ... else:
      ...     ...
      ... """), indent=4))
      Module(
          body=[
              For(
                  target=Name(id='x', ctx=Store()),
                  iter=Name(id='y', ctx=Load()),
                  body=[
                      Expr(
                          value=Constant(value=Ellipsis))],
                  orelse=[
                      Expr(
                          value=Constant(value=Ellipsis))])],
          type_ignores=[])

class ast.While(test, body, orelse)

   "while" 루프. "test"는 ("Compare" 노드와 같은) 조건을 보유합니다.

      >> print(ast.dump(ast.parse("""
      ... while x:
      ...    ...
      ... else:
      ...    ...
      ... """), indent=4))
      Module(
          body=[
              While(
                  test=Name(id='x', ctx=Load()),
                  body=[
                      Expr(
                          value=Constant(value=Ellipsis))],
                  orelse=[
                      Expr(
                          value=Constant(value=Ellipsis))])],
          type_ignores=[])

class ast.Break
class ast.Continue

   "break"와 "continue" 문.

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

class ast.Try(body, handlers, orelse, finalbody)

   "try" 블록. "ExceptHandler" 노드의 리스트인 "handlers"를 제외한, 모
   든 어트리뷰트는 실행할 노드의 리스트입니다.

      >>> print(ast.dump(ast.parse("""
      ... try:
      ...    ...
      ... except Exception:
      ...    ...
      ... except OtherException as e:
      ...    ...
      ... else:
      ...    ...
      ... finally:
      ...    ...
      ... """), indent=4))
      Module(
          body=[
              Try(
                  body=[
                      Expr(
                          value=Constant(value=Ellipsis))],
                  handlers=[
                      ExceptHandler(
                          type=Name(id='Exception', ctx=Load()),
                          body=[
                              Expr(
                                  value=Constant(value=Ellipsis))]),
                      ExceptHandler(
                          type=Name(id='OtherException', ctx=Load()),
                          name='e',
                          body=[
                              Expr(
                                  value=Constant(value=Ellipsis))])],
                  orelse=[
                      Expr(
                          value=Constant(value=Ellipsis))],
                  finalbody=[
                      Expr(
                          value=Constant(value=Ellipsis))])],
          type_ignores=[])

class ast.ExceptHandler(type, name, body)

   단일 "except" 절. "type"은 일치할 예외 형이며, 일반적으로 "Name" 노
   드(또는 모두 잡는 "except:" 절의 경우는 "None")입니다. "name"은 예
   외를 담을 이름을 위한 원시 문자열이거나, 절에 "as foo"가 없으면
   "None"입니다. "body"는 노드의 리스트입니다.

      >>> print(ast.dump(ast.parse("""\
      ... try:
      ...     a + 1
      ... except TypeError:
      ...     pass
      ... """), indent=4))
      Module(
          body=[
              Try(
                  body=[
                      Expr(
                          value=BinOp(
                              left=Name(id='a', ctx=Load()),
                              op=Add(),
                              right=Constant(value=1)))],
                  handlers=[
                      ExceptHandler(
                          type=Name(id='TypeError', ctx=Load()),
                          body=[
                              Pass()])],
                  orelse=[],
                  finalbody=[])],
          type_ignores=[])

class ast.With(items, body, type_comment)

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

   type_comment

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

class ast.withitem(context_expr, optional_vars)

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

      >>> print(ast.dump(ast.parse("""\
      ... with a as b, c as d:
      ...    something(b, d)
      ... """), indent=4))
      Module(
          body=[
              With(
                  items=[
                      withitem(
                          context_expr=Name(id='a', ctx=Load()),
                          optional_vars=Name(id='b', ctx=Store())),
                      withitem(
                          context_expr=Name(id='c', ctx=Load()),
                          optional_vars=Name(id='d', ctx=Store()))],
                  body=[
                      Expr(
                          value=Call(
                              func=Name(id='something', ctx=Load()),
                              args=[
                                  Name(id='b', ctx=Load()),
                                  Name(id='d', ctx=Load())],
                              keywords=[]))])],
          type_ignores=[])


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

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

   함수 정의.

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

   * "args" is an "arguments" node.

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

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

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

   type_comment

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

class ast.Lambda(args, body)

   "lambda"는 표현식 내에서 사용할 수 있는 최소 함수 정의입니다.
   "FunctionDef"와 달리, "body"는 단일 노드를 보유합니다.

      >>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
      Module(
          body=[
              Expr(
                  value=Lambda(
                      args=arguments(
                          posonlyargs=[],
                          args=[
                              arg(arg='x'),
                              arg(arg='y')],
                          kwonlyargs=[],
                          kw_defaults=[],
                          defaults=[]),
                      body=Constant(value=Ellipsis)))],
          type_ignores=[])

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

   함수의 인자.

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

   * "vararg"와 "kwarg"는 "*args, **kwargs" 매개 변수를 참조하는 단일
     "arg" 노드입니다.

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

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

class ast.arg(arg, annotation, type_comment)

   리스트의 단일 인자. "arg"는 인자 이름의 원시 문자열이고,
   "annotation"은 "Str"이나 "Name" 노드와 같은 어노테이션입니다.

   type_comment

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

      >>> print(ast.dump(ast.parse("""\
      ... @decorator1
      ... @decorator2
      ... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
      ...     pass
      ... """), indent=4))
      Module(
          body=[
              FunctionDef(
                  name='f',
                  args=arguments(
                      posonlyargs=[],
                      args=[
                          arg(
                              arg='a',
                              annotation=Constant(value='annotation')),
                          arg(arg='b'),
                          arg(arg='c')],
                      vararg=arg(arg='d'),
                      kwonlyargs=[
                          arg(arg='e'),
                          arg(arg='f')],
                      kw_defaults=[
                          None,
                          Constant(value=3)],
                      kwarg=arg(arg='g'),
                      defaults=[
                          Constant(value=1),
                          Constant(value=2)]),
                  body=[
                      Pass()],
                  decorator_list=[
                      Name(id='decorator1', ctx=Load()),
                      Name(id='decorator2', ctx=Load())],
                  returns=Constant(value='return annotation'))],
          type_ignores=[])

class ast.Return(value)

   "return" 문.

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

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

   "yield"나 "yield from" 표현식. 이들은 표현식이라서, 반환된 값이 사
   용되지 않으면 "Expr" 노드에 래핑 되어야 합니다.

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

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

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

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

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

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

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

   클래스 정의.

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

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

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

   * "starargs"와 "kwargs"는 함수 호출에서와같이 각각 단일 노드입니다.
     starargs는 베이스 클래스 리스트에 연결하도록 확장되고, kwargs는
     메타 클래스로 전달됩니다.

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

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

      >>> print(ast.dump(ast.parse("""\
      ... @decorator1
      ... @decorator2
      ... class Foo(base1, base2, metaclass=meta):
      ...     pass
      ... """), indent=4))
      Module(
          body=[
              ClassDef(
                  name='Foo',
                  bases=[
                      Name(id='base1', ctx=Load()),
                      Name(id='base2', ctx=Load())],
                  keywords=[
                      keyword(
                          arg='metaclass',
                          value=Name(id='meta', ctx=Load()))],
                  body=[
                      Pass()],
                  decorator_list=[
                      Name(id='decorator1', ctx=Load()),
                      Name(id='decorator2', ctx=Load())])],
          type_ignores=[])


Async와 await
-------------

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

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

class ast.Await(value)

   "await" 표현식. "value"는 기다릴 대상입니다. "AsyncFunctionDef"의
   본문에서만 유효합니다.

   >>> print(ast.dump(ast.parse("""\
   ... async def f():
   ...     await other_func()
   ... """), indent=4))
   Module(
       body=[
           AsyncFunctionDef(
               name='f',
               args=arguments(
                   posonlyargs=[],
                   args=[],
                   kwonlyargs=[],
                   kw_defaults=[],
                   defaults=[]),
               body=[
                   Expr(
                       value=Await(
                           value=Call(
                               func=Name(id='other_func', ctx=Load()),
                               args=[],
                               keywords=[])))],
               decorator_list=[])],
       type_ignores=[])

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

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

참고:

  문자열이 "ast.parse()"로 구문 분석될 때, 반환된 트리의 연산자 노드
  ("ast.operator", "ast.unaryop", "ast.cmpop", "ast.boolop" 및
  "ast.expr_context"의 서브 클래스)는 싱글톤이 됩니다. 어느 하나의 변
  경 사항은 같은 값으로 등장하는 다른 모든 곳에 반영됩니다 (예를 들어
  "ast.Add").


"ast" 도우미
============

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

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

   소스를 AST 노드로 구문 분석합니다. "compile(source, filename, mode,
   ast.PyCF_ONLY_AST)"와 동등합니다.

   "type_comments=True"가 제공되면, 구문 분석기는 **PEP 484**와 **PEP
   526**에 지정된 형 주석을 확인하고 반환하도록 수정됩니다. 이는
   "compile()"에 전달된 플래그에 "ast.PyCF_TYPE_COMMENTS"를 추가하는
   것과 같습니다. 이것은 잘못 배치된 형 주석에 대한 문법 에러를 보고합
   니다. 이 플래그가 없으면, 형 주석은 무시되고, 선택한 AST 노드의
   "type_comment" 필드는 항상 "None"입니다. 또한, "# type: ignore" 주
   석의 위치는 "Module"의 "type_ignores" 어트리뷰트로 반환됩니다 (그렇
   지 않으면 항상 빈 리스트입니다).

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

   또한, "feature_version"을 튜플 "(major, minor)"로 설정하면 해당 파
   이썬 버전의 문법을 사용하여 구문 분석을 시도합니다. 현재 "major"는
   "3"과 같아야 합니다. 예를 들어, "feature_version=(3, 4)"를 설정하면
   변수 이름으로 "async"와 "await"를 사용할 수 있습니다. 가장 낮은 지
   원 버전은 "(3, 4)"입니다; 가장 높은 것은 "sys.version_info[0:2]"입
   니다.

   If source contains a null character ('0'), "ValueError" is raised.

      경고:

        Note that successfully parsing source code into an AST object
        doesn't guarantee that the source code provided is valid
        Python code that can be executed as the compilation step can
        raise further "SyntaxError" exceptions. For instance, the
        source "return 42" generates a valid AST node for a return
        statement, but it cannot be compiled alone (it needs to be
        inside a function node).In particular, "ast.parse()" won't do
        any scoping checks, which the compilation step does.

   경고:

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

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

ast.unparse(ast_obj)

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

   경고:

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

   경고:

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

   버전 3.9에 추가.

ast.literal_eval(node_or_string)

   파이썬 리터럴 이나 컨테이너 디스플레이를 포함하는 표현식 노드나 문
   자열을 안전하게 평가합니다. 제공된 문자열이나 노드는 다음과 같은 파
   이썬 리터럴 구조로만 구성될 수 있습니다: 문자열, 바이트열, 숫자, 튜
   플, 리스트, 딕셔너리, 집합, 불리언 및 "None".

   값을 직접 구문 분석할 필요 없이 신뢰할 수 없는 소스의 파이썬 값을
   포함하는 문자열을 안전하게 평가하는 데 사용할 수 있습니다. 예를 들
   어 연산자나 인덱싱이 개입한, 임의의 복잡한 표현식을 평가할 수 없습
   니다.

   경고:

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

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

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

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"을 반환합니다.

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

   버전 3.8에 추가.

ast.fix_missing_locations(node)

   "compile()"로 노드 트리를 컴파일할 때, 컴파일러는 지원하는 모든 노
   드에 대해 "lineno"와 "col_offset" 어트리뷰트를 기대합니다. 생성된
   노드를 채울 때는 이것이 다소 지루하므로, 이 도우미는 이러한 어트리
   뷰트를 재귀적으로 아직 설정되지 않은 위치에 부모 노드의 값으로 설정
   하여 추가합니다. *node*부터 재귀적으로 작동합니다.

ast.increment_lineno(node, n=1)

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

ast.copy_location(new_node, old_node)

   가능하면 소스 위치("lineno", "col_offset", "end_lineno" 및
   "end_col_offset")를 *old_node*에서 *new_node*로 복사하고,
   *new_node*를 반환합니다.

ast.iter_fields(node)

   *node*에 존재하는 "node._fields"의 각 필드에 대해 "(fieldname,
   value)" 튜플을 산출합니다.

ast.iter_child_nodes(node)

   *node*의 모든 직접 자식 노드, 즉 노드인 모든 필드와 노드 리스트인
   필드의 모든 항목을 산출합니다.

ast.walk(node)

   *node*로 시작하는 트리(*node* 자체를 포함합니다)의 모든 자손 노드를
   지정된 순서 없이 재귀적으로 산출합니다. 이는 노드를 제자리에서 수정
   하고 문맥을 신경 쓰지 않을 때 유용합니다.

class ast.NodeVisitor

   추상 구문 트리를 걷고 발견된 모든 노드에 대해 방문자 함수를 호출하
   는 노드 방문자 베이스 클래스. 이 함수는 "visit()" 메서드에 의해 전
   달되는 값을 반환할 수 있습니다.

   이 클래스는 서브 클래싱하고자 하는 것이며, 서브 클래스는 방문자 메
   서드를 추가합니다.

   visit(node)

      노드를 방문합니다. 기본 구현은 "self.visit_*classname*"이라는 메
      서드를 호출하는데, 여기서 *classname* 은 노드 클래스의 이름입니
      다. 또는 이 메서드가 없으면 "generic_visit()"를 호출합니다.

   generic_visit(node)

      이 방문자는 노드의 자식에 대해 "visit()"를 호출합니다.

      방문자가 "generic_visit()"를 호출하거나 직접 방문하지 않는 한,
      사용자 정의 방문자 메서드가 있는 노드의 자식 노드는 방문 되지 않
      음에 유의하십시오.

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

   버전 3.8부터 폐지: 메서드 "visit_Num()", "visit_Str()",
   "visit_Bytes()", "visit_NameConstant()" 및 "visit_Ellipsis()"는 이
   제 폐지되었고 향후 파이썬 버전에서는 호출되지 않을 것입니다. 모든
   상수 노드를 처리하려면 "visit_Constant()" 메서드를 추가하십시오.

class ast.NodeTransformer

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

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

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

      class RewriteName(NodeTransformer):

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

   작업 중인 노드에 자식 노드가 있으면 자식 노드를 직접 변환하거나 노
   드에 대한 "generic_visit()" 메서드를 먼저 호출해야 함을 염두에 두십
   시오.

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

   "NodeTransformer"가 위치 정보(가령 "lineno")를 제공하지 않고 (원래
   트리의 일부가 아닌) 새 노드를 도입하면, 위치 정보를 다시 계산하려면
   "fix_missing_locations()"를 새 서브 트리로 호출해야 합니다:

      tree = ast.parse('foo', mode='eval')
      new_tree = fix_missing_locations(RewriteName().visit(tree))

   일반적으로 다음과 같이 변환기를 사용합니다:

      node = YourTransformer().visit(node)

ast.dump(node, annotate_fields=True, include_attributes=False, *, indent=None)

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

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

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


컴파일러 플래그
===============

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

ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

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

   버전 3.8에 추가.

ast.PyCF_ONLY_AST

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

ast.PyCF_TYPE_COMMENTS

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

   버전 3.8에 추가.


명령 줄 사용법
==============

버전 3.9에 추가.

"ast" 모듈은 명령 줄에서 스크립트로 실행될 수 있습니다. 다음과 같이 간
단합니다:

   python -m ast [-m <mode>] [-a] [infile]

다음과 같은 옵션이 허용됩니다:

-h, --help

   도움말 메시지를 표시하고 종료합니다.

-m <mode>
--mode <mode>

   "parse()"의 *mode* 인자와 같이, 컴파일해야 하는 코드 종류를 지정합
   니다.

--no-type-comments

   형 주석을 구문 분석하지 않습니다.

-a, --include-attributes

   줄 번호와 열 오프셋과 같은 어트리뷰트를 포함합니다.

-i <indent>
--indent <indent>

   AST에서 노드 들여쓰기(스페이스 수).

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

더 보기:

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

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

  leoAst.py는 토큰과 ast 노드 사이에 양방향 링크를 삽입하여 파이썬 프
  로그램의 토큰 기반과 구문 분석 트리 기반 뷰를 통합합니다.

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

  Parso는 다른 파이썬 버전(여러 Python 버전에서)에 대한 에러 복구와 왕
  복 구문 분석(round-trip parsing)을 지원하는 파이썬 파서입니다. Parso
  는 여러분의 파이썬 파일에 있는 여러 구문 에러를 나열 할 수도 있습니
  다.
