ast — 추상 구문 트리

ast — 추상 구문 트리 (Abstract syntax trees)

(소스: Lib/ast.py)

ast 모듈은 파이썬 애플리케이션이 파이썬 추상 구문 문법의 트리를 처리하도록 도와줘요. 추상 구문 자체는 파이썬 릴리스마다 바뀔 수 있는데, 이 모듈은 현재 문법이 어떤지 프로그램적으로 알아내는 데 도와줘요.

추상 구문 트리는 내장 compile() 함수에 플래그 ast.PyCF_ONLY_AST를 넘기거나, 이 모듈이 제공하는 parse() 헬퍼를 사용해 생성할 수 있어요. 결과는 모든 클래스가 ast.AST를 상속하는 객체들의 트리예요. 추상 구문 트리는 내장 compile() 함수로 파이썬 코드 객체로 컴파일될 수 있어요.

출처: Python documentation

본문

추상 문법 (Abstract grammar)

추상 문법은 ASDL로 정의돼요. ASDL의 네 내장 타입은 identifier, int, string, constant예요. 최상위 module은 다음 변형(variant)을 가지는 mod 노드로 시작해요.

  • `Module(stmt* body, type_ignore*
  • type_ignores), Interactive(stmt* body), Expression(expr body), FunctionType(expr* argtypes, expr returns)`

stmt(문장) 노드에는 FunctionDef, AsyncFunctionDef, ClassDef, Return, Delete, Assign, TypeAlias, AugAssign, AnnAssign, For, AsyncFor, While, If, With, AsyncWith, Match, Raise, Try, TryStar, Assert, Import 등이 있고, expr(표현식), operator, excepthandler, keyword, alias, withitem, match_case, type_param, type_ignore 같은 노드 타입들이 정의돼 있어요.

노드 클래스 (Node classes)

파이썬의 추상 구문 문법의 각 요소에는 그 문법을 정의하는 구체적인 노드 클래스가 있어요. 이 클래스들은 AST에서 파생된다는 점을 제외하면 그 구성 요소들이 필드 속성으로 정의돼 있다는 점을 제외하면 _ast 모듈에 정의된 노드 클래스들로 정의돼요. _ast 노드 클래스들은 _ast.AST에서 파생되고 그 안에 _fields 속성이 있어요. ast의 클래스들은 사실 문법을 파싱해서 정의되는데, _ast 클래스들을 일대일로 복제하고 각 노드에 _field_types, _attributes 같은 추가 메타데이터를 더해요.

노드 클래스들은 다음 범주로 구성돼요.

  • 루트 노드: Module, Interactive, Expression, FunctionType
  • 리터럴: Constant, FormattedValue, JoinedStr, List, Tuple, Set, Dict
  • 변수: Name, Load, Store, Del
  • 표현식: Starred, ListComp, SetComp, DictComp, GeneratorExp, Await, Yield, YieldFrom, Compare, Call, keyword, IfExp, Attribute, NamedExpr, Slice, 연산자 노드들(Add, Sub, ...)
  • 서브스크립팅: Subscript
  • 컴프리헨션: comprehension
  • 문장: 앞서 본 stmt 노드들
  • import: Import, ImportFrom, alias
  • 제어 흐름: If, For, While, Break, Continue, Try, TryStar, ExceptHandler, Match, match_case
  • 패턴 매칭: MatchValue, MatchSingleton, MatchSequence, MatchMapping, MatchClass, MatchStar, MatchAs, MatchOr
  • 타입 어노테이션: arg, arguments
  • 타입 매개변수: TypeVar, ParamSpec, TypeVarTuple, TypeAlias, type_param
  • 함수·클래스 정의: FunctionDef, AsyncFunctionDef, ClassDef
  • async/await: AsyncFunctionDef, AsyncFor, AsyncWith, Await

각 노드 클래스는 repr()에 트리 구조를 보여주는 _fields_attributes를 갖고, 주석/타입 어노테이션을 위한 lineno, col_offset, end_lineno, end_col_offset 같은 위치 속성도 가져요.

ast 헬퍼

  • ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1): 소스를 파싱해 AST를 반환. mode는 'exec'(기본), 'eval', 'single'. type_comments=True면 타입 주석도 파싱. feature_version으로 3.14 같은 특정 버전 문법을 지정해 파싱할 수 있어요.
  • ast.literal_eval(node_or_string): 문자열이나 AST 노드를 안전하게 파이썬 리터럴로 평가. 문자열·바이트·숫자·튜플·리스트·딕트·집합·불·None만 허용.
  • ast.get_source_segment(source, node, *, padded=False): 주어진 AST 노드에 해당하는 소스 코드 세그먼트를 반환 (node.lineno, node.end_lineno 기반).
  • ast.dump(node, *, annotate_fields=True, include_attributes=False, indent=None): AST 노드의 들여쓰기된 표현을 반환.
  • ast.copy_location(new_node, old_node): old_node에서 new_node로 위치 정보를 복사.
  • ast.fix_missing_locations(node): 누락된 위치를 부모에서 상속해 채움.
  • ast.increment_lineno(node, n=1): 노드의 줄 번호를 n만큼 증가.
  • ast.iter_fields(node), ast.iter_child_nodes(node), ast.walk(node): 노드 트리 순회 헬퍼. walk는 깊이 우선으로 모든 자손 노드를 반환.
  • ast.PyCF_ONLY_AST: compile()에 넘겨 AST만 생성하게 하는 컴파일러 플래그.
  • 노드의 위치/끝 위치 관리: lineno, col_offset, end_lineno, end_col_offset 사용.

컴파일러 플래그 (Compiler flags)

ast 모듈은 PyCF_ONLY_AST 외에도 PyCF_TYPE_COMMENTS, PyCF_ALLOW_TOP_LEVEL_AWAIT 같은 컴파일러 플래그와 PyCF_ALLOW_TOP_LEVEL_AWAIT 등을 정의해요.

커맨드라인 사용

  • python -m ast (또는 python -m ast <file.py>): 소스 파일을 파싱해 AST 덤프를 출력해요. -m ast file.py는 해당 파일의 AST를, 인자 없이는 stdin에서 읽어 AST를 출력해요. --type-comments, --no-type-comments, --feature-version VERSION 옵션을 지원해요.

AST는 코드 분석, 리팩터링 도구, linter, 코드 생성 등에서 파이썬 코드를 구조적으로 다룰 때 핵심적인 역할을 해요.

더 알아보기 (Learn more)