Astroid: Python Abstract Syntax Tree with Inference

4.1.2 · active · verified Sat Mar 28

Astroid is a Python library that provides an extended abstract syntax tree (AST) with inference capabilities, primarily used by Pylint for static code analysis. It reconstructs Python's built-in `_ast` module's tree, adding richer nodes with methods and attributes for static inference and local scope analysis. It can also build partial ASTs from live Python objects. As of version 4.1.2, it supports Python 3.10 and newer.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a Python code string into an Astroid AST. It then iterates through the top-level nodes of the module to identify function definitions and their arguments. It also shows a basic traversal within a function to find specific name usages (e.g., 'print').

from astroid import parse
from astroid.nodes import Module, FunctionDef, Name

code = """
def greet(name):
    return f"Hello, {name}!"

def farewell(name):
    print(f"Goodbye, {name}.")
"""

# Parse the code into an Astroid module
module_node: Module = parse(code)

print(f"Module name: {module_node.name}")

# Iterate over nodes to find functions
for node in module_node.body:
    if isinstance(node, FunctionDef):
        print(f"  Found function: {node.name}")
        # Access arguments
        for arg in node.args.args:
            print(f"    Argument: {arg.name}")
        # Example: Find 'print' calls (simple traversal)
        for child_node in node.body:
            if isinstance(child_node, Name) and child_node.name == 'print':
                print(f"      Function '{node.name}' uses 'print'.")

view raw JSON →