CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pyright

Static type checker for Python with command-line tool and language server capabilities

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

json-output.mddocs/

JSON Output

Structured diagnostic and analysis output for integration with development tools and CI/CD pipelines.

Capabilities

JSON Output Mode

Enable structured output format for machine consumption.

pyright --outputjson [options] files...

All output is directed to stdout as JSON, with console messages redirected to stderr.

Main Results Structure

The primary output structure containing all analysis results.

interface PyrightJsonResults {
  version: string;                                    // Pyright version
  time: string;                                       // Analysis timestamp
  generalDiagnostics: PyrightJsonDiagnostic[];       // Diagnostic messages
  summary: PyrightJsonSummary;                        // Analysis summary
  typeCompleteness?: PyrightTypeCompletenessReport;  // Optional completeness report
}

Usage Example:

pyright --outputjson src/ > analysis.json

Diagnostic Structure

Individual diagnostic messages with location and severity information.

interface PyrightJsonDiagnostic {
  file: string;                    // File path where diagnostic occurred
  severity: SeverityLevel;         // Diagnostic severity level
  message: string;                 // Human-readable diagnostic message
  range?: Range;                   // Optional source location range
  rule?: string;                   // Optional diagnostic rule identifier
}

type SeverityLevel = "error" | "warning" | "information";

Summary Statistics

Aggregate information about the analysis results.

interface PyrightJsonSummary {
  filesAnalyzed: number;    // Total number of files analyzed
  errorCount: number;       // Number of error diagnostics
  warningCount: number;     // Number of warning diagnostics  
  informationCount: number; // Number of information diagnostics
  timeInSec: number;        // Analysis duration in seconds
}

Position and Range Types

Source code location information following LSP conventions.

interface Range {
  start: Position;  // Start position of the range
  end: Position;    // End position of the range
}

interface Position {
  line: number;       // Line number (0-based)
  character: number;  // Character offset within line (0-based)
}

Type Completeness Report

Detailed analysis of type annotation completeness for packages (available with --verifytypes).

interface PyrightTypeCompletenessReport {
  packageName: string;                              // Name of the analyzed package
  packageRootDirectory?: string;                    // Package root directory path
  moduleName: string;                               // Primary module name
  moduleRootDirectory?: string;                     // Module root directory path
  ignoreUnknownTypesFromImports: boolean;           // Whether external unknowns are ignored
  pyTypedPath?: string;                            // Path to py.typed file
  exportedSymbolCounts: PyrightSymbolCount;        // Statistics for exported symbols
  otherSymbolCounts: PyrightSymbolCount;           // Statistics for other symbols
  missingFunctionDocStringCount: number;           // Functions without docstrings
  missingClassDocStringCount: number;              // Classes without docstrings
  missingDefaultParamCount: number;                // Parameters without default values
  completenessScore: number;                       // Overall completeness score (0.0-1.0)
  modules: PyrightPublicModuleReport[];            // Module-level reports
  symbols: PyrightPublicSymbolReport[];            // Symbol-level reports
}

Usage Example:

pyright --verifytypes mypackage --outputjson > completeness.json

Symbol Count Statistics

Categorized counts of symbols by type knowledge status.

interface PyrightSymbolCount {
  withKnownType: number;      // Symbols with fully known types
  withAmbiguousType: number;  // Symbols with partially known types
  withUnknownType: number;    // Symbols with unknown types
}

Module Report

Information about analyzed modules.

interface PyrightPublicModuleReport {
  name: string;  // Module name
}

Symbol Report

Detailed information about individual symbols in the public API.

interface PyrightPublicSymbolReport {
  category: string;                           // Symbol category (function, class, variable, etc.)
  name: string;                              // Fully qualified symbol name
  referenceCount: number;                    // Number of references to this symbol
  isTypeKnown: boolean;                      // Whether the symbol's type is fully known
  isTypeAmbiguous: boolean;                  // Whether the symbol's type is ambiguous
  isExported: boolean;                       // Whether the symbol is exported from its module
  diagnostics: PyrightJsonDiagnostic[];     // Diagnostics associated with this symbol
  alternateNames?: string[];                 // Optional alternate names for the symbol
}

Example JSON Output

Basic Analysis Result:

{
  "version": "1.1.405",
  "time": "1699123456789",
  "generalDiagnostics": [
    {
      "file": "/path/to/file.py",
      "severity": "error",
      "message": "Cannot assign to variable \"x\" of type \"int\" with value of type \"str\"",
      "range": {
        "start": { "line": 10, "character": 4 },
        "end": { "line": 10, "character": 15 }
      },
      "rule": "reportGeneralTypeIssues"
    }
  ],
  "summary": {
    "filesAnalyzed": 25,
    "errorCount": 3,
    "warningCount": 7,
    "informationCount": 2,
    "timeInSec": 1.234
  }
}

Type Completeness Report:

{
  "version": "1.1.405",
  "time": "1699123456789",
  "generalDiagnostics": [],
  "summary": {
    "filesAnalyzed": 15,
    "errorCount": 0,
    "warningCount": 2,
    "informationCount": 0,
    "timeInSec": 0.856
  },
  "typeCompleteness": {
    "packageName": "mypackage",
    "moduleName": "mypackage",
    "ignoreUnknownTypesFromImports": false,
    "exportedSymbolCounts": {
      "withKnownType": 45,
      "withAmbiguousType": 3,
      "withUnknownType": 2
    },
    "otherSymbolCounts": {
      "withKnownType": 123,
      "withAmbiguousType": 8,
      "withUnknownType": 5
    },
    "missingFunctionDocStringCount": 12,
    "missingClassDocStringCount": 3,
    "missingDefaultParamCount": 8,
    "completenessScore": 0.89,
    "modules": [
      { "name": "mypackage" },
      { "name": "mypackage.utils" }
    ],
    "symbols": [
      {
        "category": "function",
        "name": "mypackage.main_function",
        "referenceCount": 5,
        "isTypeKnown": true,
        "isTypeAmbiguous": false,
        "isExported": true,
        "diagnostics": []
      }
    ]
  }
}

Processing JSON Output

Python Example:

import json
import subprocess

# Run pyright and capture JSON output
result = subprocess.run(
    ["pyright", "--outputjson", "src/"],
    capture_output=True,
    text=True
)

# Parse JSON results
analysis = json.loads(result.stdout)

# Process diagnostics
for diagnostic in analysis["generalDiagnostics"]:
    if diagnostic["severity"] == "error":
        print(f"Error in {diagnostic['file']}: {diagnostic['message']}")

# Check summary
summary = analysis["summary"]
print(f"Analyzed {summary['filesAnalyzed']} files")
print(f"Found {summary['errorCount']} errors, {summary['warningCount']} warnings")

Integration Patterns

CI/CD Pipeline Integration:

#!/bin/bash
# Type check and generate report
pyright --outputjson src/ > pyright-report.json

# Parse results and set exit code
if [ $(jq '.summary.errorCount' pyright-report.json) -gt 0 ]; then
  echo "Type checking failed"
  exit 1
fi

Development Tooling:

const { exec } = require('child_process');
const fs = require('fs');

exec('pyright --outputjson src/', (error, stdout, stderr) => {
  const results = JSON.parse(stdout);
  
  // Extract diagnostics for IDE integration
  const diagnostics = results.generalDiagnostics.map(d => ({
    file: d.file,
    line: d.range?.start.line || 0,
    message: d.message,
    severity: d.severity
  }));
  
  // Send to IDE or save to file
  fs.writeFileSync('diagnostics.json', JSON.stringify(diagnostics, null, 2));
});

Output Filtering

JSON output respects the --level option:

# Only errors in JSON output
pyright --outputjson --level error src/

# All diagnostics in JSON output  
pyright --outputjson --level information src/

API Stability

The JSON output interfaces are publicly documented and stable. These schemas are considered part of Pyright's public API contract.

Compatibility

JSON output format is stable and versioned:

  • version field indicates the Pyright version that generated the output
  • Schema additions are backward-compatible
  • New fields may be added but existing fields won't change meaning
  • Consumers should handle unknown fields gracefully

Install with Tessl CLI

npx tessl i tessl/npm-pyright

docs

cli-tool.md

index.md

json-output.md

language-server.md

tile.json