Skip to content

Blocks

blocks

Top-level symbol block extraction from a libcst Module.

Block dataclass

A top-level symbol definition extracted from a module.

Carries the CST statement that defines the symbol, the leading formatting lines that immediately precede it (used to preserve # --- Section --- comments), and the set of external names referenced by its body.

Source code in packages/axm-anvil/src/axm_anvil/_cst/blocks.py
Python
@dataclass
class Block:
    """A top-level symbol definition extracted from a module.

    Carries the CST statement that defines the symbol, the leading
    formatting lines that immediately precede it (used to preserve
    ``# --- Section ---`` comments), and the set of external names
    referenced by its body.
    """

    name: str
    node: cst.BaseStatement
    leading_lines: list[cst.EmptyLine] = field(default_factory=list)
    referenced_names: set[str] = field(default_factory=set)

extract_blocks(tree, symbol_names)

Extract Block records for each requested top-level symbol.

Supports ClassDef, FunctionDef, Assign, and AnnAssign at module scope. Missing symbols are silently omitted.

Source code in packages/axm-anvil/src/axm_anvil/_cst/blocks.py
Python
def extract_blocks(tree: cst.Module, symbol_names: Sequence[str]) -> list[Block]:
    """Extract ``Block`` records for each requested top-level symbol.

    Supports ``ClassDef``, ``FunctionDef``, ``Assign``, and ``AnnAssign``
    at module scope. Missing symbols are silently omitted.
    """
    wanted = set(symbol_names)
    blocks: list[Block] = []
    for index, stmt in enumerate(tree.body):
        leading = _leading_lines_for(tree, stmt, index)
        if isinstance(stmt, cst.ClassDef | cst.FunctionDef):
            if stmt.name.value in wanted:
                blocks.append(_make_block(stmt.name.value, stmt, leading))
            continue
        if isinstance(stmt, cst.SimpleStatementLine):
            assign_name = _assigned_name_in(stmt, wanted)
            if assign_name is not None:
                blocks.append(_make_block(assign_name, stmt, leading))
    return blocks