CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-types--pyflakes

Type stubs for pyflakes, a Python source code analysis tool designed to detect errors in Python files

Overview
Eval results
Files

ast-checker.mddocs/

AST Checker and Analysis Engine

Core checker functionality providing detailed AST analysis, scope management, and binding tracking. The Checker class is the heart of pyflakes, performing static analysis by parsing Python code into Abstract Syntax Trees and tracking variable usage across different scopes.

Capabilities

Main Checker Class

The primary analysis engine that processes AST nodes and manages scope hierarchies to detect various code issues.

class Checker:
    """
    Main AST checker for Python code analysis.
    
    Attributes:
    - nodeDepth: int, current AST traversal depth
    - offset: tuple[int, int] | None, position offset for error reporting
    - builtIns: set[str], built-in names to recognize
    - deadScopes: list[Any], scopes that are no longer active
    - messages: list[Any], collected analysis messages
    - filename: str, name of file being analyzed
    - withDoctest: bool, whether to analyze doctest blocks
    - scopeStack: list[Scope], stack of active scopes
    - exceptHandlers: list[Any], active exception handlers
    - root: ast.AST, root AST node being analyzed
    """
    
    def __init__(
        self,
        tree: ast.AST,
        filename: str = ...,
        builtins: Iterable[str] | None = ...,
        withDoctest: bool = ...,
        file_tokens: tuple[Any, ...] = ...,
    ) -> None:
        """
        Initialize checker with AST tree and configuration.
        
        Parameters:
        - tree: ast.AST, parsed AST tree to analyze
        - filename: str, filename for error reporting
        - builtins: Iterable[str] | None, additional built-in names
        - withDoctest: bool, analyze doctest blocks
        - file_tokens: tuple[Any, ...], tokenized source for advanced analysis
        """

Key Methods:

def report(self, messageClass: Callable[_P, Message], *args: _P.args, **kwargs: _P.kwargs) -> None: ...
def addBinding(self, node: ast.AST, value: Binding) -> None: ...  
def handleChildren(self, tree: ast.AST, omit: _OmitType = ...) -> None: ...
def pushScope(self, scopeClass: type[Scope] = ...) -> None: ...
def popScope(self) -> None: ...

Properties:

@property
def futuresAllowed(self) -> bool:
    """Whether __future__ imports are allowed at current position."""

@property
def annotationsFutureEnabled(self) -> bool:
    """Whether annotations __future__ import is active."""

@property
def scope(self) -> Scope:
    """Current active scope."""

Scope and Binding Management

Binding Classes

Base classes for tracking name bindings and their usage throughout the code.

class Binding:
    """
    Base class for name bindings.
    
    Attributes:
    - name: str, the bound name
    - source: ast.AST | None, AST node where binding occurs
    - used: Literal[False] | tuple[Any, ast.AST], usage tracking
    """
    
    def __init__(self, name: str, source: ast.AST | None) -> None: ...
    def redefines(self, other: Binding) -> bool:
        """Check if this binding redefines another binding."""

class Definition(Binding):
    """Base class for name definitions."""

class Importation(Definition):
    """
    Import statement binding.
    
    Attributes:
    - fullName: str, full module name
    - redefined: list[Any], names redefined by this import
    """
    
    def __init__(self, name: str, source: ast.AST | None, full_name: str | None = ...) -> None: ...
    
    @property
    def source_statement(self) -> str:
        """Source import statement text."""

Scope Classes

Different types of scopes for tracking variable visibility and lifetime.

class Scope(dict[str, Binding]):
    """
    Base scope class mapping names to bindings.
    
    Attributes:
    - importStarred: bool, whether scope has star imports
    """

class ModuleScope(Scope):
    """Module-level scope."""

class FunctionScope(Scope):
    """
    Function scope with additional function-specific tracking.
    
    Attributes:
    - usesLocals: bool, whether function uses locals()
    - globals: set[str], names declared global
    - returnValue: Any, return value tracking
    - isGenerator: bool, whether function is a generator
    """
    
    def __init__(self) -> None: ...
    def unusedAssignments(self) -> Iterator[tuple[str, Binding]]:
        """Iterate over unused assignments in this scope."""

class ClassScope(Scope):
    """Class scope."""

Core Analysis Methods

Methods for managing the analysis process, scope handling, and message reporting.

def report(self, messageClass: Callable[_P, Message], *args: _P.args, **kwargs: _P.kwargs) -> None:
    """
    Report an analysis message.
    
    Parameters:
    - messageClass: Message class to instantiate
    - args: Positional arguments for message
    - kwargs: Keyword arguments for message
    """

def addBinding(self, node: ast.AST, value: Binding) -> None:
    """
    Add a name binding to current scope.
    
    Parameters:
    - node: AST node where binding occurs
    - value: Binding object representing the name
    """

def pushScope(self, scopeClass: type[Scope] = ...) -> None:
    """
    Push new scope onto scope stack.
    
    Parameters:
    - scopeClass: Type of scope to create
    """

def popScope(self) -> None:
    """Pop current scope from scope stack."""

Deferred Processing

Methods for handling analysis that must be delayed until after initial AST traversal.

def deferFunction(self, callable: _AnyFunction) -> None:
    """
    Defer function analysis until after initial pass.
    
    Parameters:
    - callable: Function to call during deferred processing
    """

def deferAssignment(self, callable: _AnyFunction) -> None:
    """
    Defer assignment analysis for complex cases.
    
    Parameters:
    - callable: Function to call during deferred processing
    """

def runDeferred(self, deferred: _AnyFunction) -> None:
    """
    Execute deferred analysis function.
    
    Parameters:
    - deferred: Previously deferred function to execute
    """

Scope and Binding Management

Binding Classes

Base classes for tracking name bindings and their usage throughout the code.

class Binding:
    """
    Base class for name bindings.
    
    Attributes:
    - name: str, the bound name
    - source: ast.AST | None, AST node where binding occurs
    - used: Literal[False] | tuple[Any, ast.AST], usage tracking
    """
    
    def __init__(self, name: str, source: ast.AST | None) -> None: ...
    def redefines(self, other: Binding) -> bool:
        """Check if this binding redefines another binding."""

class Definition(Binding):
    """Base class for name definitions."""

class Builtin(Definition):
    """Built-in name binding."""
    def __init__(self, name: str) -> None: ...

Import Bindings

Specialized binding classes for different types of import statements.

class Importation(Definition):
    """
    Import statement binding.
    
    Attributes:
    - fullName: str, full module name
    - redefined: list[Any], names redefined by this import
    """
    
    def __init__(self, name: str, source: ast.AST | None, full_name: str | None = ...) -> None: ...
    
    @property
    def source_statement(self) -> str:
        """Source import statement text."""

class ImportationFrom(Importation):
    """
    From-import binding.
    
    Attributes:
    - module: str, source module name
    - real_name: str, actual imported name
    """
    
    def __init__(self, name: str, source: ast.AST, module: str, real_name: str | None = ...) -> None: ...

class StarImportation(Importation):
    """Star import binding (from module import *)."""
    def __init__(self, name: str, source: ast.AST) -> None: ...

class FutureImportation(ImportationFrom):
    """
    Future import binding.
    
    Attributes:
    - used: tuple[Any, ast.AST], always marked as used
    """
    def __init__(self, name: str, source: ast.AST, scope) -> None: ...

Other Binding Types

class Argument(Binding):
    """Function argument binding."""

class Assignment(Binding):
    """Assignment binding."""

class Annotation(Binding):
    """Type annotation binding."""
    def redefines(self, other: Binding) -> Literal[False]:
        """Annotations never redefine other bindings."""

class FunctionDefinition(Definition):
    """Function definition binding."""

class ClassDefinition(Definition):
    """Class definition binding."""

class ExportBinding(Binding):
    """
    Export binding for __all__ declarations.
    
    Attributes:
    - names: list[str], exported names
    """
    def __init__(self, name: str, source: ast.AST, scope: Scope) -> None: ...

Scope Classes

Different types of scopes for tracking variable visibility and lifetime.

class Scope(dict[str, Binding]):
    """
    Base scope class mapping names to bindings.
    
    Attributes:
    - importStarred: bool, whether scope has star imports
    """

class ModuleScope(Scope):
    """Module-level scope."""

class FunctionScope(Scope):
    """
    Function scope with additional function-specific tracking.
    
    Attributes:
    - usesLocals: bool, whether function uses locals()
    - alwaysUsed: ClassVar[set[str]], names always considered used
    - globals: set[str], names declared global
    - returnValue: Any, return value tracking
    - isGenerator: bool, whether function is a generator
    """
    
    def __init__(self) -> None: ...
    def unusedAssignments(self) -> Iterator[tuple[str, Binding]]:
        """Iterate over unused assignments in this scope."""

class ClassScope(Scope):
    """Class scope."""

class GeneratorScope(Scope):
    """Generator expression scope."""

class DoctestScope(ModuleScope):
    """Doctest block scope."""

Utility Functions

Helper functions for AST analysis and format string parsing.

def getAlternatives(n: ast.If | ast.Try) -> list[ast.AST]:
    """Get alternative execution branches from if/try statements."""

def counter(items: Iterable[_T]) -> dict[_T, int]:
    """Count occurrences of items in iterable."""

def iter_child_nodes(node: ast.AST, omit: _OmitType = ..., _fields_order: _FieldsOrder = ...) -> Iterator[ast.AST]:
    """Iterate over child AST nodes with optional field omission."""

def getNodeName(node: ast.AST) -> str:
    """Extract name from AST node."""

def is_typing_overload(value: Binding, scope_stack) -> bool:
    """Check if binding represents a typing.overload decorator."""

def parse_percent_format(s: str) -> tuple[_PercentFormat, ...]:
    """Parse percent-style format strings for validation."""

Constants and Patterns

# Python version compatibility
PY38_PLUS: bool
PYPY: bool

# AST node types
FOR_TYPES: tuple[type[ast.For], type[ast.AsyncFor]]

# Regular expression patterns
TYPE_COMMENT_RE: Pattern[str]
TYPE_IGNORE_RE: Pattern[str]
TYPE_FUNC_RE: Pattern[str]
MAPPING_KEY_RE: Pattern[str]
CONVERSION_FLAG_RE: Pattern[str]
WIDTH_RE: Pattern[str]
PRECISION_RE: Pattern[str]
LENGTH_RE: Pattern[str]

# String constants
ASCII_NON_ALNUM: str
VALID_CONVERSIONS: frozenset[str]
TYPING_MODULES: frozenset[Literal["typing", "typing_extensions"]]

Usage Example:

import ast
from pyflakes.checker import Checker
from pyflakes.reporter import Reporter
import sys

# Parse Python code
code = """
import os
import sys
x = undefined_var
"""

tree = ast.parse(code)
reporter = Reporter(sys.stderr, sys.stderr)

# Create and run checker
checker = Checker(tree, "example.py")
print(f"Found {len(checker.messages)} issues")

# Access detailed analysis results
for message in checker.messages:
    print(f"Line {message.lineno}: {message}")

Install with Tessl CLI

npx tessl i tessl/pypi-types--pyflakes

docs

ast-checker.md

code-analysis.md

error-messages.md

index.md

report-generation.md

tile.json