An abstract syntax tree for Python with inference support.
npx @tessl/cli install tessl/pypi-astroid@3.3.0An abstract syntax tree for Python with inference support. Astroid provides a common base representation of Python source code that extends the built-in _ast module with additional methods, attributes, and static inference capabilities. It serves as the foundational library powering pylint's static code analysis capabilities.
pip install astroidimport astroidMost common usage patterns:
from astroid import parse, MANAGER
from astroid.nodes import NodeNG, Module, ClassDef, FunctionDefimport astroid
# Parse Python source code into an astroid AST
source_code = '''
def greet(name):
return f"Hello, {name}!"
class Person:
def __init__(self, name):
self.name = name
'''
# Parse the source code
module = astroid.parse(source_code)
# Navigate the AST
for node in module.body:
print(f"Node type: {type(node).__name__}")
if hasattr(node, 'name'):
print(f"Name: {node.name}")
# Use inference capabilities
function_node = module.body[0] # The greet function
for inferred in function_node.infer():
print(f"Inferred type: {type(inferred).__name__}")Astroid's architecture consists of several key components:
The node hierarchy is based on Python's _ast module but with enhanced capabilities for static analysis, making it ideal for linting tools, code analysis utilities, and development tools that need deep understanding of Python code structure and semantics.
Primary functions for converting Python source code and objects into astroid AST trees, with support for files, strings, modules, and classes.
def parse(code: str, module_name: str = "", path: str | None = None, apply_transforms: bool = True) -> nodes.Module
def extract_node(code: str, module_name: str = "") -> nodes.NodeNG | list[nodes.NodeNG]Comprehensive set of node classes representing all Python language constructs, from expressions and statements to scoped nodes like classes and functions.
class NodeNG:
def infer(self, context: InferenceContext | None = None) -> Iterator[InferenceResult]
def as_string(self) -> str
def accept(self, visitor) -> Any
class Module(LocalsDictNodeNG):
name: str
def wildcard_import_names(self) -> list[str]
class ClassDef(LocalsDictNodeNG):
name: str
bases: list[NodeNG]
def mro(self) -> list[ClassDef]
def ancestors(self) -> Iterator[ClassDef]Central management system for building, caching, and retrieving astroid AST trees from various sources including files, modules, and living objects.
class AstroidManager:
def ast_from_file(self, filepath: str, modname: str | None = None, fallback: bool = True, source: bool = False) -> Module
def ast_from_string(self, data: str, modname: str = "", filepath: str | None = None) -> Module
def ast_from_module_name(self, modname: str, context_file: str | None = None, use_cache: bool = True) -> Module
def clear_cache(self) -> NoneAdvanced static inference capabilities that determine types and values of expressions, supporting complex Python features like descriptors, metaclasses, and dynamic attributes.
class InferenceContext:
nodes_inferred: int
callcontext: CallContext | None
boundnode: NodeNG | None
def clone(self) -> InferenceContext
def inference_tip(func: Callable) -> CallableComprehensive exception hierarchy for handling various error conditions during AST building, inference, and analysis operations.
class AstroidError(Exception): ...
class AstroidBuildingError(AstroidError): ...
class InferenceError(AstroidError): ...
class NameInferenceError(InferenceError): ...
class AttributeInferenceError(InferenceError): ...Foundation classes for instances, methods, and other inferred objects that represent runtime Python objects within the static analysis context.
class BaseInstance:
def infer(self, context: InferenceContext | None = None) -> Iterator[BaseInstance]
class Instance(BaseInstance):
def getattr(self, name: str, context: InferenceContext | None = None) -> list[NodeNG]
class BoundMethod:
bound: NodeNG
proxy: UnboundMethodfrom typing import Iterator, Any, Callable
from enum import Enum
class Context(Enum):
Load = 1
Store = 2
Del = 3
InferenceResult = NodeNG | BaseInstance | type[Uninferable]