Python type inferencer that analyzes code without requiring explicit type annotations
npx @tessl/cli install tessl/pypi-pytype@2024.10.0A static type checker and inferencer for Python that analyzes code without requiring explicit type annotations. PyType performs type inference on plain Python code to detect common programming errors like misspelled attributes and incorrect function calls, while also enforcing user-provided type annotations when present.
pip install pytypeimport pytypeFor direct API usage:
from pytype import io
from pytype import config
from pytype import analyzeFor working with PyTD (Python Type Declaration) system:
from pytype.pytd import pytd
from pytype.pytd import pytd_utils
from pytype.pyi import parserfrom pytype import io
# Check types in Python source code
source_code = '''
def add_numbers(x, y):
return x + y
result = add_numbers("hello", 42) # This will cause a type error
'''
try:
# Perform type checking
result = io.check_py(source_code)
print("Type checking completed successfully")
except Exception as e:
print(f"Type checking failed: {e}")from pytype import io
# Generate .pyi type stub from source code
source_code = '''
class Calculator:
def add(self, x, y):
return x + y
def multiply(self, x, y):
return x * y
'''
# Generate PyTD AST
pyi_ast = io.generate_pyi_ast(source_code)
# Generate .pyi string
pyi_string = io.generate_pyi(source_code)
print(pyi_string)from pytype import config
from pytype import io
# Create configuration options
options = config.Options.create()
options.python_version = (3, 11)
options.output = "/path/to/output.pyi"
# Process a single file
result = io.process_one_file(options)PyType's architecture consists of several key components:
This design enables PyType to analyze large Python codebases incrementally, generate precise type information, and integrate with existing Python development workflows through multiple interfaces.
High-level API for type checking and inference operations. These functions provide the primary programmatic interface to PyType's analysis capabilities.
def check_py(src, options=None, loader=None): ...
def generate_pyi_ast(src, options=None, loader=None): ...
def generate_pyi(src, options=None, loader=None): ...
def process_one_file(options): ...Comprehensive configuration system for controlling PyType's behavior, including Python version targeting, output formats, error handling, and analysis depth settings.
class Options:
def __init__(argv_or_options, command_line=False): ...
@classmethod
def create(): ...
def make_parser(): ...Python Type Declaration system for representing, manipulating, and optimizing type information. Provides the foundation for PyType's type representation and stub file generation.
class TypeDeclUnit: ...
class Class: ...
class Function: ...
def Print(ast, multiline_args=False): ...
def Optimize(ast, builtins, **kwargs): ...Parser for Python type stub files (.pyi) that converts textual type declarations into PyTD AST representations for analysis and manipulation.
def parse_string(src, filename=None, options=None): ...
def parse_pyi(src, filename, options): ...
def canonical_pyi(pyi, multiline_args=False, options=None): ...Complete set of command-line tools for different PyType workflows, from single-file analysis to project-wide type checking and stub generation.
pytype [files...] # Analyze Python projects
pytype-single file.py # Analyze single files
pytd [options] file.pytd # Process PyTD files
merge-pyi file.py file.pyi # Merge type stubs into source
annotate-ast file.py # Add type annotations to AST
pyxref [files...] # Generate cross-referencesInfrastructure for loading and resolving Python modules, PyTD files, and type information with support for custom import mappings and pickled type data.
def create_loader(options, missing_modules=()): ...
class Loader: ...
class Module: ...class AnalysisResult:
"""Result of PyType analysis operations."""
def __init__(self, ast, errors, loader): ...
class Analysis:
"""Analysis context and results."""
def __init__(self, context, ast, ast_deps): ...class PostprocessingError(Exception):
"""Error during configuration postprocessing."""class UsageError(Exception):
"""Top-level usage errors."""