### Run TypeCoverage Demo Scripts Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Executes the demo scripts included with typecoverage to showcase basic usage examples and verify the installation. ```bash # Basic usage examples python demos/basic_usage.py ``` -------------------------------- ### Install TypeCoverage for Development Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Installs typecoverage in editable mode for development or directly using setup.py. This allows for direct code changes to be reflected without reinstallation. ```bash # Install in editable/development mode pip install -e . # Or install directly python setup.py install ``` -------------------------------- ### Install TypeCoverage from Source Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Installs typecoverage from the current development source. This involves cloning or downloading the repository, navigating to the directory, and installing dependencies using pip. ```bash # Clone or download the repository # Navigate to the project directory pip install -r requirements.txt ``` -------------------------------- ### TypeCoverage Real-World Example: Gradual Adoption Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md An example demonstrating a gradual adoption strategy for type coverage, focusing initially on function signatures and context lines, while ignoring certain variable types. ```bash # Start with just function signatures typecoverage --no-ignore-underscore-vars \ --context-lines 2 \ src/core.py ``` -------------------------------- ### TypeCoverage Real-World Example: Check Entire Project Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md A command-line example for checking an entire project recursively, including statistics, and excluding specific directories like `__pycache__` and `tests`. ```bash typecoverage --recursive --statistics \ --exclude __pycache__,tests \ src/ ``` -------------------------------- ### TypeCoverage Real-World Example: CI/CD Integration Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md An example of configuring typecoverage for CI/CD pipelines, outputting results in JSON format, ensuring a non-zero exit code on issues, and saving the report to a file. ```bash typecoverage --format json \ --exit-nonzero-on-issues \ --output typecoverage-report.json \ src/ ``` -------------------------------- ### TypeCoverage CLI Options for Statistics and Formatting Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Demonstrates common command-line options for typecoverage, including showing statistics, including context lines, outputting in JSON format, and saving the report to a file. ```bash typecoverage --statistics myfile.py typecoverage --context-lines 3 myfile.py typecoverage --format json myfile.py typecoverage --output report.txt myfile.py ``` -------------------------------- ### Troubleshoot common issues Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Resolve common installation errors, filter noise, and debug performance bottlenecks. ```bash python -m typecoverage myfile.py typecoverage --ignore-underscore-vars src/ typecoverage --context-lines 0 src/ | grep "Missing return type" typecoverage --format json src/ 2>&1 | jq '.' ``` -------------------------------- ### Display typecoverage Help Information Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Provides the command to display all available options and arguments for the typecoverage CLI. This is the primary way to get help and discover all functionalities. ```bash # Show all available options typecoverage --help ``` -------------------------------- ### Get typecoverage Version Information Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Shows the command to display the currently installed version of the typecoverage CLI. This is useful for checking compatibility or reporting issues. ```bash typecoverage --version ``` -------------------------------- ### Run typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Demonstrates the two primary ways to invoke the typecoverage CLI: using the Python module or the installed command. This is the fundamental command structure for all typecoverage operations. ```bash # Using the module python -m typecoverage [OPTIONS] [TARGETS...] # Using installed command (if installed) typecoverage [OPTIONS] [TARGETS...] ``` -------------------------------- ### Install typecoverage from source Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Home.md Instructions for cloning the repository and installing the necessary dependencies for development. ```bash git clone cd typecoverage-project pip install -r requirements.txt ``` -------------------------------- ### TypeCoverage CLI Options for Exit Codes Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Demonstrates how to configure typecoverage's exit codes for CI/CD integration. Options allow exiting with a non-zero code if any issues are found or if the number of issues exceeds a threshold. ```bash # Exit with code 1 if any issues found typecoverage --exit-nonzero-on-issues myfile.py # Exit with code 1 if 5 or more issues found typecoverage --fail-under 5 myfile.py ``` -------------------------------- ### TypeCoverage CLI Options for Filtering Ignored Variables Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Explains and demonstrates how to control which variables typecoverage ignores by default and how to include more variable types in the analysis using command-line flags. ```bash # Include underscore variables typecoverage --no-ignore-underscore-vars myfile.py # Include all variable types typecoverage --no-ignore-underscore-vars \ --no-ignore-for-targets \ --no-ignore-except-vars \ --no-ignore-context-vars \ myfile.py ``` -------------------------------- ### Run typecoverage Demo Mode Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Illustrates how to run typecoverage in demo mode, which executes built-in demonstrations of its features. This is a helpful way to quickly see typecoverage in action. ```bash # Run built-in demonstrations typecoverage --demo ``` -------------------------------- ### Analyze Python Files with TypeCoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Demonstrates basic command-line usage of typecoverage to analyze Python files. It covers analyzing a single file, multiple files, and recursively analyzing a directory. ```bash python -m typecoverage myfile.py typecoverage myfile.py typecoverage file1.py file2.py file3.py typecoverage --recursive src/ ``` -------------------------------- ### TypeCoverage API Script for Project Analysis Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md A Python script demonstrating how to use the typecoverage API to analyze all Python files within a directory, compute statistics, and print a summary of type annotation issues. ```python #!/usr/bin/env python3 """Analyze project and generate report.""" from typecoverage import typecoverage from pathlib import Path def analyze_project(): checker = typecoverage() # Find all Python files py_files = list(Path("src").rglob("*.py")) # Analyze files issues, errors = checker.analyze_targets( *py_files, context_lines=1, ignore_underscore_vars=True, ) # Generate report stats = checker.compute_stats(issues) print(f"Analyzed {len(py_files)} files") print(f"Found {stats.total} type annotation issues") print(f" Arguments: {stats.by_type.get('untyped-argument', 0)}") print(f" Returns: {stats.by_type.get('untyped-return', 0)}") print(f" Variables: {stats.by_type.get('untyped-variable', 0)}") if errors: print(f"\nErrors: {len(errors)}") for error in errors[:3]: # Show first 3 print(f" {error}") if __name__ == "__main__": analyze_project() ``` -------------------------------- ### TypeCoverage CLI Usage Examples Source: https://context7.com/kairos-xx/typecoverage/llms.txt Provides various command-line examples for using TypeCoverage to analyze Python files and directories. It covers basic usage, recursive analysis, including context lines, JSON output for CI/CD, excluding paths, setting quality gates, saving output to files, and running the built-in demo. ```bash # Basic file analysis python -m typecoverage myfile.py typecoverage myfile.py # Recursive directory analysis with statistics typecoverage --recursive --statistics src/ # Include context lines for easier fixing typecoverage --context-lines 3 --statistics src/main.py # JSON output for CI/CD pipelines typecoverage --format json --exit-nonzero-on-issues --recursive src/ > report.json # Exclude specific paths and file patterns typecoverage --recursive --exclude __pycache__,tests,build --extensions .py,.pyx src/ # Fail CI if too many issues (quality gate) typecoverage --fail-under 10 --exit-nonzero-on-issues --recursive src/ # Save output to file typecoverage --recursive --statistics --output coverage-report.txt src/ # Include all variable types (disable default filters) typecoverage --no-ignore-underscore-vars --no-ignore-for-targets --no-ignore-except-vars src/ # Run built-in demo typecoverage --demo # Show version typecoverage --version ``` -------------------------------- ### Analyze Python Files with typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Provides examples of how to use the typecoverage CLI to analyze Python files. It covers analyzing single files, multiple files, the current directory, and using glob patterns for flexible file selection. ```bash # Analyze a single file typecoverage myfile.py # Analyze multiple files typecoverage file1.py file2.py file3.py # Analyze current directory typecoverage . # Analyze with glob patterns typecoverage "*.py" typecoverage "src/**/*.py" ``` -------------------------------- ### Run typecoverage via Command Line Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Home.md Examples of using the typecoverage CLI to analyze individual files or entire directories recursively. ```bash # Using the package python -m typecoverage myfile.py # Or if installed typecoverage --recursive --statistics src/ ``` -------------------------------- ### Install Typecoverage from source and package Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Provides standard commands for installing the Typecoverage tool from a repository or local source code. ```bash git clone cd typecoverage-project pip install -r requirements.txt # Install in development mode pip install -e . # Or install directly python setup.py install ``` -------------------------------- ### Initialize Typecoverage Python API Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Verifies that the typecoverage core module is correctly installed and configured. It instantiates the checker class to ensure the environment is ready for programmatic use. ```python from typecoverage.core import typecoverage checker = typecoverage() print('Configuration loaded successfully') ``` -------------------------------- ### Setup and Development Workflow for Typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Commands to initialize the development environment, format code, run linting checks, and execute the test suite with coverage reporting. ```bash # Set up development environment pip install -r requirements.txt # Run code formatting black . --line-length 79 isort . -l 79 -m 1 ruff format . --line-length 79 # Run linting ruff check . pyright # Run tests with coverage pytest tests/ --cov=typecoverage --cov-report=term-missing ``` -------------------------------- ### Configure typecoverage with pyproject.toml Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Demonstrates how to configure typecoverage using a `pyproject.toml` file. This allows for persistent settings that are automatically applied when the CLI is run in the project's root directory. ```toml [tool.typecoverage] recursive = true statistics = true context-lines = 2 exclude = ["tests", "__pycache__"] ignore-underscore-vars = true exit-nonzero-on-issues = true ``` -------------------------------- ### Analyze Live Python Objects with TypeCoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Illustrates analyzing live Python objects, such as functions, using the typecoverage API. The `typecoverage` class provides methods to inspect objects and report type annotation issues. ```python from typecoverage import typecoverage def my_function(x, y): return x + y checker = typecoverage() issues, errors = checker.analyze_object(my_function) for issue in issues: print(f"{issue.type}: {issue.name} at line {issue.line}") ``` -------------------------------- ### Integrate with Makefile Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Define standard make targets for running type coverage analysis and generating reports. ```makefile typecoverage: typecoverage --recursive --statistics src/ typecoverage-ci: typecoverage --exit-nonzero-on-issues --recursive src/ typecoverage-report: typecoverage --recursive --statistics --context-lines 2 --output reports/typecoverage.txt src/ ``` -------------------------------- ### Python Suppression Comments for TypeCoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Shows how to use standard Python suppression comments (`# type: ignore`, `# noqa`) to ignore specific type annotation issues reported by typecoverage. Supports tool-specific comments as well. ```python def my_function(x, y): # type: ignore return x + y def another_function(x, y): # noqa: ANN001,ANN201 return x + y ``` -------------------------------- ### Control Output Format with typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Demonstrates how to control the output format of the typecoverage analysis. It covers selecting human-readable text (default) and machine-readable JSON formats. ```bash # Human-readable text (default) typecoverage --format text myfile.py # Machine-readable JSON typecoverage --format json myfile.py ``` -------------------------------- ### Optimize performance and file selection Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Configure file inclusion/exclusion patterns and processing limits to handle large codebases efficiently. ```bash typecoverage "src/**/*.py" "lib/**/*.py" "tools/*.py" typecoverage --exclude __pycache__,node_modules,.git . typecoverage --extensions .py --recursive src/ typecoverage --context-lines 0 --recursive src/ ``` -------------------------------- ### Integrate with Pre-commit and GitHub Actions Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Configure automated type checks using pre-commit hooks and GitHub Actions workflows. ```yaml # .pre-commit-config.yaml repos: - repo: local hooks: - id: typecoverage entry: typecoverage args: [--exit-nonzero-on-issues, --recursive] # .github/workflows/typecoverage.yml jobs: typecoverage: runs-on: ubuntu-latest steps: - run: typecoverage --format json --exit-nonzero-on-issues --recursive --output typecoverage-report.json src/ ``` -------------------------------- ### Specify Target Paths for typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Illustrates how to specify different types of targets for the typecoverage CLI, including file paths, directory paths (both recursive and non-recursive), and glob patterns for precise file matching. ```bash # File Paths typecoverage src/main.py typecoverage /absolute/path/to/file.py # Directory Paths # Non-recursive (files in directory only) typecoverage src/ # Recursive (include subdirectories) typecoverage --recursive src/ # Glob Patterns # All .py files in current directory typecoverage "*.py" # All .py files recursively typecoverage "**/*.py" # Specific patterns typecoverage "src/**/test_*.py" ``` -------------------------------- ### Configure Failure Conditions for typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Demonstrates how to configure the typecoverage CLI to exit with a non-zero status code under specific conditions, such as when any issues are found or when the number of issues falls below a specified threshold. ```bash # Exit with code 1 if any issues found typecoverage --exit-nonzero-on-issues myfile.py # Exit with code 1 if 5 or more issues found typecoverage --fail-under 5 myfile.py # Combine both conditions typecoverage --exit-nonzero-on-issues --fail-under 10 src/ ``` -------------------------------- ### Include Statistics in typecoverage Output Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Explains how to include a summary of issue counts in the typecoverage analysis report using the `--statistics` option. This provides a quick overview of the findings. ```bash # Include issue count summary typecoverage --statistics myfile.py ``` -------------------------------- ### Run Typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Executes the typecoverage tool on a single Python file with context lines enabled. This command identifies type coverage gaps in the specified file. ```bash typecoverage --context-lines 2 single_file.py ``` -------------------------------- ### Analyze Code String with TypeCoverage Python API Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Quick-Start.md Shows how to use the typecoverage Python API to analyze a code string directly. The `detect_untyped` function takes a string of Python code and returns information about untyped elements. ```python from typecoverage import detect_untyped # Analyze code string code = """ def greet(name): return f"Hello, {name}!" """ result = detect_untyped(code) print(result) ``` -------------------------------- ### Analyze Python Code Strings with typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Shows how the typecoverage CLI can analyze Python code directly when provided as a string argument. This is useful for quick checks of small code snippets without saving them to a file. ```bash typecoverage "def func(x): return x" ``` -------------------------------- ### Generate reports Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Output analysis results to files for documentation or badge generation. Supports text and JSON formats. ```bash typecoverage --recursive --statistics --context-lines 3 --output docs/type-coverage-report.txt src/ typecoverage --format json --statistics --recursive --output coverage.json src/ ``` -------------------------------- ### Automate with custom shell scripts Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Create reusable shell scripts for consistent type checking across development environments. ```bash # check-types.sh typecoverage --recursive --statistics --context-lines 1 --exclude __pycache__,build,dist "$@" # ci-typecoverage.sh set -e typecoverage --format json --exit-nonzero-on-issues --recursive --output typecoverage-results.json src/ ``` -------------------------------- ### Control Color Output in typecoverage CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Explains how to manage color output in the typecoverage CLI. It covers the default auto-detection behavior and how to force color output when needed, such as in environments where it might not be automatically detected. ```bash # Auto-detect color support (default) typecoverage myfile.py # Force color output typecoverage --force-color myfile.py ``` -------------------------------- ### Specify File Extensions for typecoverage Analysis Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Demonstrates how to configure the file extensions that typecoverage should consider during analysis using the `--extensions` option. This allows for targeting specific types of files beyond the default Python files. ```bash # Only Python files (default) typecoverage --extensions .py src/ # Multiple extensions typecoverage --extensions .py,.pyx src/ # Custom extensions typecoverage --extensions .py,.pyi,.pyx src/ ``` -------------------------------- ### Integrate with CI/CD pipelines Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Automate type checking in CI environments using exit codes and JSON reporting. Ensures build failure on detected type issues. ```bash typecoverage --format json --exit-nonzero-on-issues --output typecoverage-report.json --recursive src/ if typecoverage --exit-nonzero-on-issues src/; then echo "✅ No type annotation issues" else echo "❌ Type annotation issues found" fi ``` -------------------------------- ### Enforce quality gates Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Set thresholds for type coverage issues to enforce code quality standards. Useful for gradual improvement strategies. ```bash typecoverage --fail-under 10 --statistics --recursive src/ typecoverage --fail-under 50 src/ typecoverage --fail-under 25 src/ typecoverage --fail-under 10 src/ ``` -------------------------------- ### Analyze type coverage via CLI Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Perform type coverage analysis on files, directories, or specific code snippets. Supports recursive scanning, statistics generation, and context-line configuration. ```bash typecoverage --context-lines 2 myfile.py typecoverage --context-lines 1 "def my_func(x): return x" typecoverage --recursive --statistics --exclude __pycache__,tests --context-lines 1 src/ ``` -------------------------------- ### Understand typecoverage Exit Codes Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Provides a clear explanation of the different exit codes returned by the typecoverage CLI. These codes indicate the success or failure of the analysis, including whether issues were found or errors occurred. ```text - 0: Success (no issues found or analysis completed) - 1: Issues found (when using failure options) - 2: Error (invalid arguments, file not found, etc.) ``` -------------------------------- ### Enable Recursive Directory Processing in typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Explains the `--recursive` option for the typecoverage CLI, which enables the analysis of files within subdirectories. This is essential for projects with complex directory structures. ```bash # Process directories recursively typecoverage --recursive src/ # Non-recursive (default for most patterns) typecoverage src/ ``` -------------------------------- ### Exclude Files and Directories from typecoverage Analysis Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Shows how to exclude specific files or directories from the typecoverage analysis using the `--exclude` option. This is crucial for ignoring generated code, test files, or build artifacts. ```bash # Exclude files containing specific substrings typecoverage --exclude test_,__pycache__ src/ # Exclude multiple patterns typecoverage --exclude tests,docs,build src/ ``` -------------------------------- ### Control Context Lines in typecoverage Output Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Shows how to specify the number of context lines to display around each issue found during typecoverage analysis using the `--context-lines` option. This helps in understanding the location and nature of the issues. ```bash # Show 2 lines of context around each issue typecoverage --context-lines 2 myfile.py # Show 5 lines of context typecoverage --context-lines 5 myfile.py ``` -------------------------------- ### GET /compute_stats Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Calculates aggregate statistics from a sequence of identified type issues. ```APIDOC ## GET /compute_stats ### Description Processes a list of Issue objects to generate a Stats summary. ### Method GET ### Endpoint /compute_stats ### Parameters #### Request Body - **issues** (Sequence[Issue]) - Required - List of identified issues. ### Response #### Success Response (200) - **total** (int) - Total count of issues. - **by_type** (Mapping) - Count of issues grouped by IssueType. ### Response Example { "total": 10, "by_type": { "untyped-argument": 7, "untyped-return": 3 } } ``` -------------------------------- ### Comprehensive Variable Filtering in typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Illustrates how to disable the default filtering of various variable types (underscore, for-loop, exception, context manager, comprehension) simultaneously to perform a more exhaustive type coverage analysis. ```bash typecoverage \ --no-ignore-underscore-vars \ --no-ignore-for-targets \ --no-ignore-except-vars \ --no-ignore-context-vars \ --no-ignore-comprehensions \ myfile.py ``` -------------------------------- ### Specify Output Destination for typecoverage Reports Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Details how to direct the output of the typecoverage analysis to a specific file instead of the standard output using the `--output` option. This is useful for saving reports for later review or integration into other workflows. ```bash # Print to stdout (default) typecoverage myfile.py # Save to file typecoverage --output report.txt myfile.py # Save JSON report typecoverage --format json --output report.json myfile.py ``` -------------------------------- ### Filter Context Manager Variables in typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Details how to control the analysis of variables used with context managers (e.g., `with open(...) as f:`). By default, typecoverage ignores these variables. ```bash # Ignore context manager variables (default) typecoverage myfile.py # Include context manager variables typecoverage --no-ignore-context-vars myfile.py ``` -------------------------------- ### Filter Comprehension Variables in typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Explains how to control the analysis of variables introduced within list, set, or dictionary comprehensions. The default behavior is to ignore these variables. ```bash # Ignore comprehension variables (default) typecoverage myfile.py # Include comprehension variables typecoverage --no-ignore-comprehensions myfile.py ``` -------------------------------- ### Filter Exception Handler Variables in typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Shows how to control whether variables used in exception handlers (e.g., `except Exception as e:`) are considered by typecoverage. The default is to ignore them. ```bash # Ignore exception handler variables (default) typecoverage myfile.py # Include exception variables typecoverage --no-ignore-except-vars myfile.py ``` -------------------------------- ### Filter Underscore Variables in typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Demonstrates how to control whether variables prefixed with an underscore (often used for ignored or internal variables) are considered during typecoverage analysis. The default behavior is to ignore them. ```bash # Ignore underscore variables (default) typecoverage myfile.py # Include underscore variables typecoverage --no-ignore-underscore-vars myfile.py ``` -------------------------------- ### Filter For-Loop Target Variables in typecoverage Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/CLI-Guide.md Explains how to control the inclusion of variables used as targets in for-loops during typecoverage analysis. By default, these are ignored to reduce noise from common iteration patterns. ```bash # Ignore for-loop target variables (default) typecoverage myfile.py # Include for-loop variables typecoverage --no-ignore-for-targets myfile.py ``` -------------------------------- ### Run Typecoverage CLI Source: https://context7.com/kairos-xx/typecoverage/llms.txt Basic execution of the typecoverage tool from the command line to analyze a source directory. ```bash typecoverage src/ ``` -------------------------------- ### Initialize TypeCoverage Class (Python) Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Demonstrates how to initialize the main `typecoverage` class, which serves as the entry point for all type coverage analysis functionalities. ```python class typecoverage: def __init__(self) -> None ``` -------------------------------- ### Perform basic and project-wide type analysis Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Demonstrates how to initialize the typecoverage checker to analyze individual strings or entire directory structures. Returns issue lists and statistics for further processing. ```python from typecoverage import typecoverage checker = typecoverage() code = "def func(x): return x" issues, error = checker.analyze_source(name="test.py", text=code, context_lines=0) # Project analysis issues, errors = checker.analyze_targets(*py_files, context_lines=1, exclude=["__pycache__", ".git"]) stats = checker.compute_stats(issues) ``` -------------------------------- ### pyproject.toml Configuration for TypeCoverage Source: https://context7.com/kairos-xx/typecoverage/llms.txt Demonstrates how to configure TypeCoverage default options within a project's `pyproject.toml` file. This allows users to set preferences like recursive analysis, statistics, context lines, exclusions, and exit behavior without needing to specify them on the command line repeatedly. ```toml # pyproject.toml [tool.typecoverage] recursive = true statistics = true context-lines = 2 exclude = ["tests", "__pycache__", "build", "dist", ".git"] extensions = [".py"] ignore-underscore-vars = true ignore-for-targets = true ignore-except-vars = true ignore-context-vars = true ignore-comprehensions = true exit-nonzero-on-issues = true fail-under = 50 ``` -------------------------------- ### Use typecoverage Python API Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Home.md Shows how to perform simple analysis on code strings or use the typecoverage class for more advanced directory-based analysis. ```python from typecoverage import typecoverage, detect_untyped # Simple analysis issues, errors = detect_untyped("def func(x): return x") # Advanced usage checker = typecoverage() issues, errors = checker.analyze_targets("src/", recursive=True) ``` -------------------------------- ### Perform Batch Analysis Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Use the analyze_targets function to perform bulk analysis across multiple files, directories, or glob patterns. ```python from pathlib import Path from typecoverage import analyze_targets # Analyze multiple targets issues, errors = analyze_targets( "src/main.py", # Specific file Path("lib/"), # Directory path "utils/**/*.py", # Glob pattern my_function, # Live object recursive=True, exclude=["test_", "__pycache__"], context_lines=1, ) print(f"Total issues: {len(issues)}") print(f"Errors: {len(errors)}") ``` -------------------------------- ### Configure TypeCoverage via pyproject.toml Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Define static analysis settings including recursive scanning, exclusion patterns, and exit behavior in a standard TOML configuration file. ```toml [tool.typecoverage] recursive = true statistics = true context-lines = 2 exclude = ["tests", "__pycache__", "build"] ignore-underscore-vars = true exit-nonzero-on-issues = true fail-under = 50 ``` -------------------------------- ### analyze_targets Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes multiple targets including files, directories, and objects simultaneously. ```APIDOC ## POST /analyze_targets ### Description Performs bulk analysis on multiple targets, supporting recursive directory searching and path exclusions. ### Method POST ### Parameters #### Request Body - **targets** (List[TargetLike]) - Required - List of strings, paths, or objects - **recursive** (bool) - Optional - Whether to search directories recursively - **exclude** (List[str]) - Optional - Substrings to exclude from file paths ### Response #### Success Response (200) - **issues** (List[Issue]) - List of identified issues - **errors** (List[str]) - List of error messages encountered ``` -------------------------------- ### Analyze Python code for missing type annotations Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/Home.md Demonstrates how to use the detect_untyped function to identify missing type annotations in a string of Python code and retrieve summary statistics. ```python from typecoverage import detect_untyped # Analyze code string code = """ def calculate_area(length, width): return length * width """ result = detect_untyped(code, statistics=True) print(result) ``` -------------------------------- ### Analyze Multiple Targets (Python) Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes multiple targets, which can be files, directories, or live Python objects. It supports recursive searching in directories and allows specifying file extensions and exclusions. Configuration options for ignoring variables and constructs are consistent with other analysis methods. Returns a tuple of issues and a list of error messages. ```python def analyze_targets( self, *targets: TargetLike, context_lines: int = 0, recursive: bool = True, extensions: Sequence[str] = (".py",), exclude: Sequence[str] = (), ignore_underscore_vars: bool = True, ignore_comprehensions: bool = True, ignore_except_vars: bool = True, ignore_for_targets: bool = True, ignore_context_vars: bool = True, ) -> Tuple[List[Issue], List[str]] ``` ```python from typecoverage import typecoverage checker = typecoverage() issues, errors = checker.analyze_targets( "src/", "*.py", my_function, recursive=True, exclude=["test_", "__pycache__"], ) ``` -------------------------------- ### Import Typecoverage Library Components (Python) Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Imports necessary components from the typecoverage library, including the main class, utility functions, and type definitions for issues and statistics. ```python from typecoverage import typecoverage, detect_untyped, analyze_targets, Issue, IssueType, Stats ``` -------------------------------- ### Suppress Type Coverage Issues Source: https://context7.com/kairos-xx/typecoverage/llms.txt Demonstrates how to use various comment patterns to suppress type coverage warnings in Python code, including standard type ignore and linter-specific flags. ```python from typecoverage import detect_untyped code = """ # Suppress all issues on a line def legacy_function(x, y): # type: ignore return x + y # Suppress specific error codes def another_function(data): # noqa: ANN001 return process(data) # Suppress on previous line # type: ignore[reportMissingParameterType] def third_function(items, options): return items # Pyright/mypy specific def fourth_function(value): # pyright: ignore return value * 2 """ result = detect_untyped(code, statistics=True) print(result) ``` -------------------------------- ### Integrate Typecoverage into GitHub Actions Source: https://context7.com/kairos-xx/typecoverage/llms.txt Configures a CI/CD pipeline to run typecoverage on pull requests, generating a JSON report and enforcing quality gates. ```yaml name: Type Annotation Coverage on: [push, pull_request] jobs: typecoverage: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: | pip install -r requirements.txt pip install -e . - name: Run typecoverage run: | typecoverage \ --format json \ --exit-nonzero-on-issues \ --recursive \ --statistics \ --exclude __pycache__,tests \ --output typecoverage-report.json \ src/ - name: Upload report uses: actions/upload-artifact@v4 if: always() with: name: typecoverage-report path: typecoverage-report.json ``` -------------------------------- ### Define library constants and terminal colors Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Contains the current library version and ANSI escape sequences for terminal output formatting. ```python VERSION: str = "0.1.8" class Colors(Enum): RESET = "\033[0m" BOLD = "\033[1m" RED = "\033[31m" GREEN = "\033[32m" ``` -------------------------------- ### Integrate TypeCoverage into CI/CD Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Automate type coverage checks using GitHub Actions or pre-commit hooks to ensure code quality before merging. ```yaml name: Type Annotation Coverage on: [push, pull_request] jobs: typecoverage: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11' - name: Install dependencies run: pip install -r requirements.txt - name: Run typecoverage run: | typecoverage \ --format json \ --exit-nonzero-on-issues \ --recursive \ --output typecoverage-report.json \ src/ ``` ```yaml # .pre-commit-config.yaml repos: - repo: local hooks: - id: typecoverage name: typecoverage entry: typecoverage language: system args: [--exit-nonzero-on-issues, --recursive, src/] files: \.py$ ``` -------------------------------- ### Perform advanced static analysis using the TypeCoverage class Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Shows how to use the TypeCoverage class for more granular control over analysis, including recursive directory scanning and excluding specific paths. ```python from typecoverage import TypeCoverage, detect_untyped # Simple analysis result = detect_untyped("def func(x): return x", statistics=True) print(result) # Advanced analysis checker = TypeCoverage() issues, errors = checker.analyze_targets( "src/", recursive=True, context_lines=2, exclude=["__pycache__", "tests"], ) stats = checker.compute_stats(issues) print(f"Found {stats.total} issues across {len(set(i.file for i in issues))} files") ``` -------------------------------- ### Convenience module-level functions Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Provides simplified access to analysis functionality without manually instantiating the main class. ```python from typecoverage import detect_untyped, analyze_targets # Detect untyped code directly result = detect_untyped("def func(x): return x", statistics=True) # Analyze targets for issues issues, errors = analyze_targets("src/", recursive=True) print(f"Found {len(issues)} issues") ``` -------------------------------- ### TypeCoverage.render_text / render_json: Render Analysis Results Source: https://context7.com/kairos-xx/typecoverage/llms.txt Renders TypeCoverage analysis results in either human-readable text format with ANSI colors for terminal output or machine-readable JSON format suitable for CI/CD integration. This allows for flexible reporting based on the user's needs. ```python from typecoverage import TypeCoverage checker = TypeCoverage() code = """ def calculate(x, y): result = x + y return result """ issues, _ = checker.analyze_source(name="calc.py", text=code, context_lines=1) stats = checker.compute_stats(issues) # Render as colorized text for terminal text_report = checker.render_text( issues=issues, stats=stats, use_color=True # Set False for plain text ) print(text_report) # Render as JSON for tooling json_report = checker.render_json(issues=issues, stats=stats) print(json_report) # Output: # { # "version": "2.1.1", # "issues": [ # {"file": "calc.py", "line": 2, "column": 15, "type": "untyped-argument", "name": "x", "context": [...]}, # ... # ], # "by_file": {"calc.py": 4}, # "statistics": {"total": 4, "untyped-argument": 2, "untyped-return": 1, "untyped-variable": 1} # } ``` -------------------------------- ### analyze_file Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes a specific Python file on the filesystem for type coverage. ```APIDOC ## POST /analyze_file ### Description Reads a Python file from a given path and performs type coverage analysis. ### Method POST ### Parameters #### Request Body - **path** (Path) - Required - Path to the Python file - **context_lines** (int) - Required - Number of context lines to include ### Response #### Success Response (200) - **issues** (List[Issue]) - List of identified issues - **error** (Optional[str]) - Error message if analysis failed ``` -------------------------------- ### Integrate type coverage results via JSON Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Shows how to retrieve analysis results in JSON format using the detect_untyped function, allowing for programmatic parsing and custom reporting. ```python import json from typecoverage import detect_untyped result_json = detect_untyped("myfile.py", format="json", statistics=True) data = json.loads(result_json) print(f"Total issues: {data['statistics']['total']}") ``` -------------------------------- ### Analyze Python File (Python) Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes a single Python file located at a specified path. It accepts the file path and context line count, along with the same set of ignore flags as `analyze_source`. The method returns a tuple containing a list of issues and an optional error message. ```python def analyze_file( self, path: Path, *, context_lines: int, ignore_underscore_vars: bool = True, ignore_comprehensions: bool = True, ignore_except_vars: bool = True, ignore_for_targets: bool = True, ignore_context_vars: bool = True, ) -> Tuple[List[Issue], Optional[str]] ``` -------------------------------- ### Analyze Python Source Code String (Python) Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes Python source code provided as a string. It takes the source text, a pseudo-name, and context line count as primary inputs. Various boolean flags allow fine-grained control over what types of variables and constructs to ignore during analysis. Returns a tuple containing a list of detected issues and an optional error message. ```python def analyze_source( self, *, name: str, text: str, context_lines: int, ignore_underscore_vars: bool = True, ignore_comprehensions: bool = True, ignore_except_vars: bool = True, ignore_for_targets: bool = True, ignore_context_vars: bool = True, ) -> Tuple[List[Issue], Optional[str]] ``` ```python from typecoverage import typecoverage checker = typecoverage() issues, error = checker.analyze_source( name="example.py", text="def func(x): return x", context_lines=1, ) ``` -------------------------------- ### Analyze Live Python Object (Python) Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes a live Python object (like a function, class, or module) by extracting its source code. It requires the object itself and the number of context lines. An optional name hint can be provided for reporting purposes. Similar ignore flags to `analyze_source` are available. Returns a tuple of issues and an optional error message. ```python def analyze_object( self, obj: Union[CodeType, FrameType, FunctionType, Type[Any], type, ModuleType, Callable], *, context_lines: int, name_hint: Optional[str] = None, ignore_underscore_vars: bool = True, ignore_comprehensions: bool = True, ignore_except_vars: bool = True, ignore_for_targets: bool = True, ignore_context_vars: bool = True, ) -> Tuple[List[Issue], Optional[str]] ``` ```python def my_func(x, y): return x + y from typecoverage import typecoverage checker = typecoverage() issues, error = checker.analyze_object(my_func, context_lines=1) ``` -------------------------------- ### POST /detect_untyped Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes target files or code objects to identify missing type annotations and returns a formatted report. ```APIDOC ## POST /detect_untyped ### Description Analyzes specified targets for missing type annotations and returns a report in the requested format. ### Method POST ### Endpoint /detect_untyped ### Parameters #### Request Body - **targets** (TargetLike) - Required - Files, paths, or code objects to analyze. - **format** (string) - Optional - Output format: "text" or "json". Default: "text". - **statistics** (boolean) - Optional - Include summary statistics. Default: false. - **recursive** (boolean) - Optional - Recursively search directories. Default: true. - **extensions** (Sequence[str]) - Optional - File extensions to include. Default: (".py",). ### Request Example { "targets": ["myfile.py"], "format": "json", "statistics": true } ### Response #### Success Response (200) - **report** (string) - Formatted analysis report. #### Response Example { "report": "{\"total\": 5, \"by_type\": {\"untyped-argument\": 5}}" } ``` -------------------------------- ### Analyze Python code for missing type annotations using the library API Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Demonstrates how to use the detect_untyped function to analyze a string of Python code for missing type annotations. It returns a result object containing detailed information about missing arguments and return types. ```python from typecoverage import detect_untyped # Analyze code string code = """ def calculate_total(items, tax_rate): subtotal = sum(item.price for item in items) return subtotal * (1 + tax_rate) """ result = detect_untyped(code, statistics=True) print(result) ``` -------------------------------- ### Analyze Python Source Code String with TypeCoverage.analyze_source Source: https://context7.com/kairos-xx/typecoverage/llms.txt Analyzes Python source code provided as a string to find type annotation issues. It allows configuration for context lines, ignoring specific variable types, targets, or comprehensions. Returns a tuple containing a list of issues and an optional error message if parsing fails. ```python from typecoverage import TypeCoverage checker = TypeCoverage() code = """ class DataProcessor: def __init__(self, config): self.config = config self.cache = {} def process(self, data, options): result = [] for item in data: processed = self._transform(item, options) result.append(processed) return result def _transform(self, item, options): multiplier = options.get("multiplier", 1) return item * multiplier """ issues, error = checker.analyze_source( name="data_processor.py", text=code, context_lines=1, ignore_underscore_vars=True, ignore_for_targets=True, ignore_comprehensions=True, ) if error: print(f"Error: {error}") else: print(f"Found {len(issues)} type annotation issues:") for issue in issues: print(f" Line {issue.line}: {issue.type} - {issue.name}") ``` -------------------------------- ### analyze_source Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes Python source code provided as a string to detect missing type annotations. ```APIDOC ## POST /analyze_source ### Description Analyzes Python source code from a string input and returns a list of detected type coverage issues. ### Method POST ### Parameters #### Request Body - **name** (str) - Required - Pseudo-name for the source (e.g., filename) - **text** (str) - Required - Python source code string - **context_lines** (int) - Required - Number of context lines to include - **ignore_underscore_vars** (bool) - Optional - Skip variables starting with underscore - **ignore_comprehensions** (bool) - Optional - Skip variables in comprehensions ### Response #### Success Response (200) - **issues** (List[Issue]) - List of identified issues - **error** (Optional[str]) - Error message if analysis failed ### Response Example { "issues": [], "error": null } ``` -------------------------------- ### Compute and render analysis statistics Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Calculates aggregate statistics from a list of issues and renders them into human-readable text or machine-readable JSON formats. ```python stats = checker.compute_stats(issues) text_report = checker.render_text(issues=issues, stats=stats, use_color=True) json_report = checker.render_json(issues=issues, stats=stats) ``` -------------------------------- ### Detect Untyped Code with Typecoverage CLI/API Source: https://context7.com/kairos-xx/typecoverage/llms.txt Analyzes Python code (string, file, or directory) to detect missing type annotations and generates a formatted report. Supports statistics, context lines, recursive analysis, and exclusion of specific directories or files. Outputs in text or JSON format. ```python from typecoverage import detect_untyped # Analyze a code string with statistics code = """ def calculate_total(items, tax_rate): subtotal = sum(item.price for item in items) return subtotal * (1 + tax_rate) """ result = detect_untyped(code, statistics=True, context_lines=1) print(result) # Output: # Found 3 type annotation issues # # 📁 # :2:20 - Missing type annotation for argument "items" # :2:27 - Missing type annotation for argument "tax_rate" # :2:1 - Missing return type annotation "calculate_total" # # 📊 Summary # Total issues: 3 # 🔴 Missing argument types: 2 # 🟡 Missing return types: 1 # Analyze a file with JSON output json_result = detect_untyped( "src/main.py", format="json", statistics=True, recursive=True, exclude=["__pycache__", "tests"] ) import json data = json.loads(json_result) print(f"Total issues: {data['statistics']['total']}") ``` -------------------------------- ### Analyze Live Python Objects with TypeCoverage.analyze_object Source: https://context7.com/kairos-xx/typecoverage/llms.txt Analyzes live Python objects such as functions, classes, or modules by extracting their source code. This method is useful for runtime analysis and for testing the type coverage of imported modules directly within a Python script. ```python from typecoverage import TypeCoverage checker = TypeCoverage() ``` -------------------------------- ### analyze_object Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Analyzes a live Python object (function, class, module) by extracting its source code. ```APIDOC ## POST /analyze_object ### Description Inspects a live Python object and analyzes its source code for type coverage. ### Method POST ### Parameters #### Request Body - **obj** (Union[CodeType, FunctionType, ...]) - Required - The Python object to analyze - **context_lines** (int) - Required - Number of context lines to include - **name_hint** (str) - Optional - Name hint for reporting ### Response #### Success Response (200) - **issues** (List[Issue]) - List of identified issues - **error** (Optional[str]) - Error message if analysis failed ``` -------------------------------- ### Analyze Live Objects Programmatically Source: https://github.com/kairos-xx/typecoverage/blob/main/README.md Use the TypeCoverage class to analyze functions or classes at runtime. This is useful for dynamic testing or custom integration scripts. ```python from typecoverage import TypeCoverage def my_function(x, y): return x + y class MyClass: def method(self, value): return value * 2 checker = TypeCoverage() # Analyze function issues, _ = checker.analyze_object(my_function, context_lines=1) print(f"Function issues: {len(issues)}") # Analyze class issues, _ = checker.analyze_object(MyClass, context_lines=1) print(f"Class issues: {len(issues)}") ``` -------------------------------- ### Define data structures for analysis Source: https://github.com/kairos-xx/typecoverage/blob/main/docs/wiki/API-Reference.md Core dataclasses used to represent findings and aggregate statistics within the analysis engine. ```python @dataclass(frozen=True) class Issue: file: Path line: int column: int type: IssueType name: str context: List[str] @dataclass class Stats: total: int by_type: MutableMapping[IssueType, int] ```