On this page
  1. ast
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Extracting Imports & Function Definitions with ast.NodeVisitor
  7. 2. Rewriting & Unparsing Source with NodeTransformer + ast.unparse()
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

ast

Prev: array | Up: stdlib_module | Next: asyncio
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — ast
Tags: #public #python3 #stdlib


Import

import ast

Overview

Parses Python source code into an Abstract Syntax Tree (AST) for static analysis, linting, refactoring, and safe literal evaluation (ast.literal_eval). Reach for ast whenever you need to inspect or transform Python syntax reliably without executing the code—never use regex to parse Python.

Quick Start

import ast

data = ast.literal_eval("{'a': [1, 2, 3], 'ok': True}")
assert data == {"a": [1, 2, 3], "ok": True}

tree = ast.parse("def greet(name: str) -> str:\n    return f'Hi {name}'\n")
fn = tree.body[0]
assert isinstance(fn, ast.FunctionDef) and fn.name == "greet"

Implementation Walkthrough

1. Extracting Imports & Function Definitions with ast.NodeVisitor

import ast

class ImportCollector(ast.NodeVisitor):
    def __init__(self) -> None:
        self.modules: set[str] = set()

    def visit_Import(self, node: ast.Import) -> None:
        for alias in node.names:
            self.modules.add(alias.name.split(".")[0])

    def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
        if node.module:
            self.modules.add(node.module.split(".")[0])

tree = ast.parse("import os.path\nfrom pathlib import Path\n")
collector = ImportCollector()
collector.visit(tree)
assert collector.modules == {"os", "pathlib"}

2. Rewriting & Unparsing Source with NodeTransformer + ast.unparse()

import ast

class DoubleInts(ast.NodeTransformer):
    def visit_Constant(self, node: ast.Constant) -> ast.AST:
        if isinstance(node.value, int) and not isinstance(node.value, bool):
            return ast.copy_location(ast.Constant(node.value * 2), node)
        return node

tree = DoubleInts().visit(ast.parse("x = 3 + 4"))
ast.fix_missing_locations(tree)
assert ast.unparse(tree) == "x = 6 + 8"

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes