or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-pyright

Command line wrapper for pyright that manages Node.js dependencies automatically

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyright@1.1.x

To install, run

npx @tessl/cli install tessl/pypi-pyright@1.1.0

index.mddocs/

Pyright

A Python command-line wrapper over Microsoft's pyright static type checker for Python. This package eliminates the need to install Node.js or npm separately by automatically managing the Node.js environment and pyright npm package installation, making pyright accessible to Python developers without JavaScript toolchain dependencies.

Package Information

  • Package Name: pyright
  • Language: Python
  • Installation: pip install pyright
  • Recommended Installation: pip install pyright[nodejs] (more reliable Node.js binaries)

Core Imports

import pyright

For direct module access:

import pyright.cli
import pyright.langserver
import pyright.errors
import pyright.node
import pyright.utils
import pyright.types

For specific imports:

from pyright import errors
from pyright.cli import run, main, entrypoint
from pyright.langserver import run, main, entrypoint
from pyright.node import run, version, latest
from pyright.types import Target, check_target
from pyright.utils import get_cache_dir, env_to_bool

Basic Usage

Command Line Usage

# Via console script (most common)
# After installation, pyright is available as a command:
# $ pyright --help
# $ pyright src/

# Programmatic usage
from pyright.cli import run, main

# Run pyright with arguments (returns CompletedProcess)
result = run('--version')
print(result.stdout)

# Run pyright and get exit code
exit_code = main(['src/', '--outputjson'])

Language Server Usage

from pyright.langserver import run as langserver_run, main as langserver_main

# Run pyright language server
result = langserver_run('--stdio')

# Run with exit code
exit_code = langserver_main('--stdio')

Architecture

The package provides four entry points for different use cases:

  • CLI Tools: pyright and pyright-python for command-line type checking
  • Language Server: pyright-langserver and pyright-python-langserver for IDE integration
  • Node.js Management: Automatically handles Node.js installation via three strategies:
    • Global Node.js (preferred if available)
    • nodejs-wheel package (more reliable, requires [nodejs] extra)
    • nodeenv (fallback, creates isolated Node.js environment)

Capabilities

Command Line Interface

Core functions for running pyright type checking from Python code or command line.

def run(*args: str, **kwargs: Any) -> Union[subprocess.CompletedProcess[bytes], subprocess.CompletedProcess[str]]:
    """
    Execute pyright with given arguments.
    
    Parameters:
    - *args: Command line arguments to pass to pyright
    - **kwargs: Additional subprocess arguments (stdout, stderr, etc.)
    
    Returns:
    subprocess.CompletedProcess: Result of pyright execution
    """

def main(args: List[str], **kwargs: Any) -> int:
    """
    Main entry point for pyright CLI returning exit code.
    
    Parameters:
    - args: List of command line arguments
    - **kwargs: Additional subprocess arguments
    
    Returns:
    int: Exit code (0 for success, non-zero for errors)
    """

def entrypoint() -> NoReturn:
    """
    Console script entry point for pyright command.
    
    Calls main() with sys.argv[1:] and exits with the result.
    """

Language Server Interface

Functions for running pyright as a language server for IDE integration.

def run(*args: str, **kwargs: Any) -> subprocess.CompletedProcess[bytes] | subprocess.CompletedProcess[str]:
    """
    Execute pyright language server with arguments.
    
    Parameters:
    - *args: Language server arguments (typically --stdio)
    - **kwargs: Additional subprocess arguments
    
    Returns:
    subprocess.CompletedProcess: Result of language server execution
    """

def main(*args: str, **kwargs: Any) -> int:
    """
    Main entry point for language server returning exit code.
    
    Parameters:
    - *args: Language server arguments
    - **kwargs: Additional subprocess arguments
    
    Returns:
    int: Exit code
    """

def entrypoint() -> NoReturn:
    """
    Console script entry point for pyright language server.
    
    Calls main() with sys.argv[1:] and exits with the result.
    """

Node.js Management

Low-level functions for managing Node.js runtime and npm packages.

def run(target: Target, *args: str, **kwargs: Any) -> Union[subprocess.CompletedProcess[bytes], subprocess.CompletedProcess[str]]:
    """
    Execute node or npm commands using resolved binary strategy.
    
    Parameters:
    - target: Either 'node' or 'npm'
    - *args: Command line arguments to pass to the binary
    - **kwargs: Additional subprocess arguments
    
    Returns:
    subprocess.CompletedProcess: Result of command execution
    
    Raises:
    - BinaryNotFound: If required binary cannot be found
    - VersionCheckFailed: If version validation fails
    """

def version(target: Target) -> Tuple[int, ...]:
    """
    Get version information for node or npm binary.
    
    Parameters:
    - target: Either 'node' or 'npm'
    
    Returns:
    Tuple[int, ...]: Version tuple (e.g., (18, 17, 0))
    
    Raises:
    - VersionCheckFailed: If version cannot be determined
    """

def latest(package: str) -> str:
    """
    Get latest version of an npm package.
    
    Parameters:
    - package: NPM package name
    
    Returns:
    str: Latest version string
    
    Raises:
    - VersionCheckFailed: If version check fails
    """

def get_env_variables() -> Dict[str, Any]:
    """
    Get environment variables for Node.js execution.
    
    Returns:
    Dict[str, Any]: Environment variables dict
    """

def get_pkg_version(pkg: Path) -> str | None:
    """
    Parse package.json file and return version property.
    
    Parameters:
    - pkg: Path to package.json file
    
    Returns:
    str | None: Version string or None if cannot be resolved
    """

Utility Functions

Helper functions for directory management and configuration.

def get_cache_dir() -> Path:
    """
    Get user cache directory path.
    
    Returns:
    Path: Cache directory path (respects XDG_CACHE_HOME, defaults to ~/.cache)
    """

def get_env_dir() -> Path:
    """
    Get nodeenv directory path.
    
    Returns:
    Path: Directory containing nodeenv installation
    """

def get_bin_dir(*, env_dir: Path) -> Path:
    """
    Get binary directory for given environment directory.
    
    Parameters:
    - env_dir: Environment directory path
    
    Returns:
    Path: Binary directory (Scripts on Windows, bin on Unix)
    """

def env_to_bool(key: str, *, default: bool = False) -> bool:
    """
    Convert environment variable to boolean.
    
    Parameters:
    - key: Environment variable name
    - default: Default value if not set
    
    Returns:
    bool: Boolean value (recognizes '1', 't', 'on', 'true' as True)
    """

def maybe_decode(data: Union[str, bytes]) -> str:
    """
    Decode bytes to string if needed.
    
    Parameters:
    - data: String or bytes data
    
    Returns:
    str: Decoded string
    """

def get_latest_version() -> Optional[str]:
    """
    Get latest pyright-python version from PyPI.
    
    Returns:
    Optional[str]: Latest version string or None if unavailable
    """

Type Validation

Functions for validating and working with type definitions.

def check_target(value: Any) -> None:
    """
    Validate that a value is a valid Target type.
    
    Parameters:
    - value: Value to validate
    
    Raises:
    - TypeError: If value is not 'node' or 'npm'
    """

Exception Handling

class PyrightError(Exception):
    """Base exception for pyright-related errors."""
    message: str

class NodeError(PyrightError):
    """Node.js related errors."""
    pass

class BinaryNotFound(NodeError):
    """Raised when expected Node.js binary is not found."""
    path: Path
    target: Target

class VersionCheckFailed(NodeError):
    """Raised when version checking fails."""
    pass

Types

Target = Literal['node', 'npm']

class GlobalStrategy(NamedTuple):
    """Strategy using global Node.js installation."""
    type: Literal['global']
    path: Path

class NodeJSWheelStrategy(NamedTuple):
    """Strategy using nodejs-wheel package."""
    type: Literal['nodejs_wheel']

class NodeenvStrategy(NamedTuple):
    """Strategy using nodeenv installation."""
    type: Literal['nodeenv'] 
    path: Path

Strategy = Union[GlobalStrategy, NodeJSWheelStrategy, NodeenvStrategy]

Constants

Important constants used by the Node.js management system:

ENV_DIR: Path  # Environment directory path
BINARIES_DIR: Path  # Binary directory path
USE_GLOBAL_NODE: bool  # Whether to use global Node.js (default: True)
USE_NODEJS_WHEEL: bool  # Whether to use nodejs-wheel package (default: True) 
NODE_VERSION: Optional[str]  # User-specified Node.js version
VERSION_RE: Pattern  # Regular expression for version matching
PYPI_API_URL: str  # PyPI JSON API URL for version checking

# Package metadata constants (available from main pyright module)
__version__: str  # Package version (e.g., "1.1.405")
__pyright_version__: str  # Wrapped pyright version (e.g., "1.1.405")
__title__: str  # Package title
__author__: str  # Package author  
__license__: str  # Package license
__copyright__: str  # Copyright information

Environment Variables

Extensive configuration options via environment variables:

Version Control

  • PYRIGHT_PYTHON_FORCE_VERSION: Override pyright version (e.g., "1.1.400", "latest")
  • PYRIGHT_PYTHON_PYLANCE_VERSION: Use Pylance-compatible version (e.g., "2023.11.11")

Node.js Management

  • PYRIGHT_PYTHON_GLOBAL_NODE: Use global Node.js (default: True)
  • PYRIGHT_PYTHON_NODE_VERSION: Specify Node.js version for nodeenv
  • PYRIGHT_PYTHON_ENV_DIR: Custom nodeenv directory path
  • PYRIGHT_PYTHON_NODEJS_WHEEL: Use nodejs-wheel package (default: True)

Caching and Storage

  • PYRIGHT_PYTHON_CACHE_DIR: Custom cache directory
  • XDG_CACHE_HOME: XDG cache directory (respected if set)

Output and Debugging

  • PYRIGHT_PYTHON_DEBUG: Enable debug logging
  • PYRIGHT_PYTHON_VERBOSE: Show npm installation logs
  • PYRIGHT_PYTHON_IGNORE_WARNINGS: Suppress version warnings

Package Control

  • PYRIGHT_PYTHON_USE_BUNDLED_PYRIGHT: Use bundled pyright version (default: True)

Console Scripts

Four console scripts are installed:

  • pyright: Main pyright CLI command
  • pyright-python: Alias for pyright CLI
  • pyright-langserver: Pyright language server
  • pyright-python-langserver: Alias for language server

Pre-commit Integration

Support for pre-commit hooks via .pre-commit-config.yaml:

repos:
  - repo: https://github.com/RobertCraigie/pyright-python
    rev: v1.1.405
    hooks:
    - id: pyright

Installation Options

# Basic installation
pip install pyright

# Recommended: with nodejs-wheel for reliable Node.js binaries  
pip install pyright[nodejs]

# Development installation
pip install pyright[dev]

# All extras
pip install pyright[all]

Usage Examples

Basic Type Checking

from pyright.cli import run

# Check specific files
result = run('src/main.py', 'src/utils.py')
if result.returncode == 0:
    print("Type checking passed!")
else:
    print("Type checking failed")

# Check entire directory with JSON output
result = run('src/', '--outputjson')

Language Server for IDE

from pyright.langserver import run as langserver_run

# Start language server with stdio communication
result = langserver_run('--stdio')

Version Management

from pyright.node import version, latest

# Check Node.js version
node_version = version('node')
print(f"Node.js version: {'.'.join(map(str, node_version))}")

# Get latest pyright version
latest_pyright = latest('pyright')
print(f"Latest pyright: {latest_pyright}")

Error Handling

from pyright.cli import run
from pyright.errors import PyrightError, BinaryNotFound

try:
    result = run('--version')
    print(result.stdout.decode())
except BinaryNotFound as e:
    print(f"Node.js binary not found at {e.path}")
except PyrightError as e:
    print(f"Pyright error: {e.message}")