CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-astroid

An abstract syntax tree for Python with inference support.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

parsing.mddocs/

Core Parsing and Building

Primary functions and classes for converting Python source code and objects into astroid AST trees. These functions serve as the main entry points for creating astroid representations from various sources.

Capabilities

Source Code Parsing

Parse Python source code strings into astroid AST trees with full inference capabilities.

def parse(code: str, module_name: str = "", path: str | None = None, apply_transforms: bool = True) -> nodes.Module:
    """
    Parse Python source code into an astroid Module.
    
    Parameters:
    - code: Python source code to parse
    - module_name: Name to assign to the created module
    - path: File path for the source (used in error messages)
    - apply_transforms: Whether to apply registered transforms
    
    Returns:
    Module node representing the parsed code
    
    Raises:
    AstroidSyntaxError: If the code contains syntax errors
    """

Usage example:

import astroid

code = '''
def add(a, b):
    return a + b

x = add(1, 2)
'''

module = astroid.parse(code, module_name="example")
print(f"Module name: {module.name}")
print(f"Number of statements: {len(module.body)}")

Node Extraction

Extract specific nodes from source code using special markers, useful for testing and focused analysis.

def extract_node(code: str, module_name: str = "") -> nodes.NodeNG | list[nodes.NodeNG]:
    """
    Extract nodes from code using #@ markers or __() wrappers.
    
    Parameters:
    - code: Source code with extraction markers
    - module_name: Name for the containing module
    
    Returns:
    Single node or list of nodes marked for extraction
    
    Raises:
    AstroidSyntaxError: If extraction markers are malformed
    """

Usage example:

import astroid

# Using #@ marker
code_with_marker = '''
def func():
    return 42 #@
'''

node = astroid.extract_node(code_with_marker)
print(f"Extracted node: {type(node).__name__}")

# Using __() wrapper  
code_with_wrapper = '''
def func():
    return __(42)
'''

node = astroid.extract_node(code_with_wrapper)
print(f"Extracted constant value: {node.value}")

AstroidBuilder Class

Core builder class for creating astroid trees from various sources including files, strings, modules, and classes.

class AstroidBuilder:
    """Builder for astroid AST trees from various sources."""
    
    def __init__(self, manager: AstroidManager | None = None, apply_transforms: bool = True) -> None:
        """Initialize builder with optional manager and transform settings."""
    
    def file_build(self, path: str, modname: str | None = None) -> nodes.Module:
        """
        Build astroid tree from a Python file.
        
        Parameters:
        - path: Path to Python source file
        - modname: Name for the module (defaults to filename)
        
        Returns:
        Module node representing the file contents
        
        Raises:
        AstroidBuildingError: If file cannot be read or parsed
        """
    
    def string_build(self, data: str, modname: str = "", path: str | None = None) -> nodes.Module:
        """
        Build astroid tree from source string.
        
        Parameters:
        - data: Python source code
        - modname: Name for the module
        - path: Optional file path for error reporting
        
        Returns:
        Module node representing the source code
        
        Raises:
        AstroidSyntaxError: If source contains syntax errors
        """
    
    def module_build(self, module: Any, modname: str | None = None) -> nodes.Module:
        """
        Build astroid tree from a live Python module.
        
        Parameters:
        - module: Python module object
        - modname: Name for the astroid module
        
        Returns:
        Module node representing the live module
        
        Raises:
        AstroidBuildingError: If module cannot be introspected
        """

Raw Building Functions

Low-level functions for building astroid nodes from runtime Python objects.

def build_module(name: str, doc: str | None = None) -> nodes.Module:
    """Create a new Module node."""

def build_class(name: str, basenames: list[str] | None = None, doc: str | None = None) -> nodes.ClassDef:
    """Create a new ClassDef node."""

def build_function(name: str, args: list[str] | None = None, posonlyargs: list[str] | None = None, 
                  defaults: list[Any] | None = None, doc: str | None = None) -> nodes.FunctionDef:
    """Create a new FunctionDef node."""

Error Handling

The parsing system raises specific exceptions for different error conditions:

  • AstroidSyntaxError: Malformed Python syntax
  • AstroidBuildingError: General building failures (file access, module import)
  • AstroidImportError: Import resolution failures

Advanced Usage

Custom Transforms

Register transforms that modify AST nodes during building:

from astroid import MANAGER

def remove_docstrings(node):
    """Remove docstring nodes."""
    if isinstance(node, astroid.Expr) and isinstance(node.value, astroid.Const):
        if isinstance(node.value.value, str):
            return None
    return node

MANAGER.register_transform(astroid.Expr, remove_docstrings)

Module Building from Files

import astroid

# Build from file
try:
    module = astroid.parse(open('mymodule.py').read(), 'mymodule')
    print(f"Successfully parsed {module.name}")
except astroid.AstroidSyntaxError as e:
    print(f"Syntax error: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-astroid

docs

bases.md

exceptions.md

index.md

inference.md

manager.md

nodes.md

parsing.md

tile.json