Astroid: Python Abstract Syntax Tree with Inference
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
- breaking Astroid v3.0.0 and later removed support for Python 3.7.
- breaking In Astroid v4.0.0, the `manager` argument to `AstroidBuilder()` became required to alleviate circular import issues.
- deprecated Importing node classes directly from the top-level `astroid` package (e.g., `from astroid import FunctionDef`) is deprecated.
- gotcha Deeply nested code structures or complex transformations can lead to `RecursionError` during AST processing.
- breaking Astroid v3.3.0 and later removed support for Python 3.8.
- 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`.
Install
-
pip install astroid
Imports
- parse
from astroid import parse
- MANAGER
from astroid import MANAGER
- FunctionDef
from astroid.nodes import FunctionDef
- AstroidBuilder
from astroid.builder import AstroidBuilder
Quickstart
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'.")