Astroid: Python Abstract Syntax Tree with Inference

raw JSON →
4.1.2 verified Tue May 12 auth: no python install: verified quickstart: verified

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.

pip install astroid
error ModuleNotFoundError: No module named 'astroid'
cause The 'astroid' package is not installed in the Python environment.
fix
Install the 'astroid' package using pip: 'pip install astroid'.
error ImportError: No module named 'astroid'
cause The 'astroid' package is not installed or not accessible in the Python environment.
fix
Ensure 'astroid' is installed and accessible: 'pip install astroid'.
error SyntaxError: invalid syntax
cause Using Python 2 syntax in a Python 3 environment, such as 'except ValueError, ex:'.
fix
Update the syntax to be compatible with Python 3: 'except ValueError as ex:'.
error E0401: Unable to import 'mytool' (import-error)
cause Pylint cannot resolve the import due to relative import issues or missing '__init__.py' files.
fix
Ensure all necessary '__init__.py' files are present and consider using absolute imports.
error F0002: %s: %s
cause An unexpected error occurred while building the Astroid representation, often due to internal issues.
fix
Check the traceback for details and consider reporting the issue to the Astroid maintainers.
breaking Astroid v3.0.0 and later removed support for Python 3.7.
fix Upgrade your Python environment to 3.8 or newer. Current Astroid versions (4.x) require Python >=3.10.0.
breaking In Astroid v4.0.0, the `manager` argument to `AstroidBuilder()` became required to alleviate circular import issues.
fix Ensure you pass a manager instance, typically `astroid.MANAGER`, when initializing `AstroidBuilder`. E.g., `builder = AstroidBuilder(manager=astroid.MANAGER)`.
deprecated Importing node classes directly from the top-level `astroid` package (e.g., `from astroid import FunctionDef`) is deprecated.
fix Import node classes from `astroid.nodes` instead (e.g., `from astroid.nodes import FunctionDef`).
gotcha Deeply nested code structures or complex transformations can lead to `RecursionError` during AST processing.
fix Increase Python's recursion limit if encountering such errors: `import sys; sys.setrecursionlimit(YOUR_HIGHER_LIMIT)`.
breaking Astroid v3.3.0 and later removed support for Python 3.8.
fix Upgrade your Python environment to 3.9 or newer. Current Astroid versions (4.x) require Python >=3.10.0.
breaking Internal functions `infer_numpy_member`, `name_looks_like_numpy_member`, and `attribute_looks_like_numpy_member` were removed from `astroid.brain.brain_numpy_utils`.
fix Avoid using these internal functions directly, as they are no longer part of the public API. Adapt code to use public inference methods.
python os / libc status wheel install import disk
3.10 alpine (musl) - - 0.14s 20.4M
3.10 slim (glibc) - - 0.10s 21M
3.11 alpine (musl) - - 0.21s 22.3M
3.11 slim (glibc) - - 0.17s 23M
3.12 alpine (musl) - - 0.19s 14.1M
3.12 slim (glibc) - - 0.20s 15M
3.13 alpine (musl) - - 0.18s 13.8M
3.13 slim (glibc) - - 0.17s 14M
3.9 alpine (musl) - - 0.13s 19.8M
3.9 slim (glibc) - - 0.11s 20M

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