or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

bases.mdexceptions.mdindex.mdinference.mdmanager.mdnodes.mdparsing.md
tile.json

tessl/pypi-astroid

An abstract syntax tree for Python with inference support.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/astroid@3.3.x

To install, run

npx @tessl/cli install tessl/pypi-astroid@3.3.0

index.mddocs/

Astroid

An 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.

Package Information

  • Package Name: astroid
  • Language: Python
  • Installation: pip install astroid
  • Python Version: 3.9+

Core Imports

import astroid

Most common usage patterns:

from astroid import parse, MANAGER
from astroid.nodes import NodeNG, Module, ClassDef, FunctionDef

Basic Usage

import 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__}")

Architecture

Astroid's architecture consists of several key components:

  • Parser/Builder: Converts Python source code or living objects into astroid AST nodes
  • Node Classes: Extended AST nodes with inference and analysis methods
  • Manager: Caches parsed modules and manages the building process
  • Inference Engine: Provides static type inference capabilities
  • Brain Modules: Extend inference for standard library and popular packages
  • Transform System: Allows modification of AST nodes during building

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.

Capabilities

Core Parsing and Building

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]

Core Parsing

AST Node Classes

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]

AST Nodes

Manager and Building System

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) -> None

Manager System

Inference System

Advanced 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) -> Callable

Inference

Exception Handling

Comprehensive 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): ...

Exceptions

Base Classes and Objects

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: UnboundMethod

Base Classes

Types

from typing import Iterator, Any, Callable
from enum import Enum

class Context(Enum):
    Load = 1
    Store = 2
    Del = 3

InferenceResult = NodeNG | BaseInstance | type[Uninferable]