Pyright for Python

raw JSON →
1.1.408 verified Sun Mar 29 auth: no python

Pyright for Python is a command-line wrapper that simplifies the installation and execution of Microsoft's Pyright static type checker within a Python environment. Pyright itself is a fast, standards-compliant type checker written in TypeScript and executed via Node.js. This wrapper handles the complexities of downloading and managing Node.js and the Pyright npm package, allowing Python developers to use Pyright without needing a separate Node.js installation. The project is actively maintained with frequent releases, typically aligned with upstream Pyright updates.

pip install pyright
error pyright: command not found
cause The `pyright` executable is not found in the system's PATH, typically because the Python package was not installed or the virtual environment where it's installed is not active.
fix
Ensure pyright is installed via pip install pyright and that your virtual environment is activated. On Windows, ensure the Scripts directory of your Python environment is in the PATH.
error Failed to install Pyright
cause The `pyright` Python wrapper encountered an issue downloading Node.js or installing the underlying Pyright npm package, often due to network connectivity problems, firewall restrictions, or insufficient permissions.
fix
Check your internet connection and proxy settings. Ensure the user has write permissions in the installation directory. You might try pip install --no-cache-dir pyright to force a fresh download.
error [Errno 2] No such file or directory: '/path/to/.pyright/node/node'
cause The `pyright` wrapper successfully downloaded a Node.js archive but failed to extract it properly, or the extracted executable is missing or not accessible, preventing `pyright` from running.
fix
Try clearing the pyright cache (usually in ~/.pyright or AppData/Local/pyright on Windows) and reinstalling pyright via pip install --force-reinstall pyright. Ensure sufficient disk space and permissions.
error ReportMissingImports: Import "some_module" could not be resolved
cause Pyright cannot find the specified module because it's either not installed in the Python environment being analyzed or the `pyrightconfig.json` (or `pyproject.toml`) is not correctly configured to include the necessary paths or virtual environment.
fix
Ensure the module is installed (pip install some_module) in the environment Pyright is checking. If using a virtual environment, verify venvPath and venv in your pyrightconfig.json or add the module's path to extraPaths.
gotcha The `pyright-python` wrapper handles Node.js installation via `nodeenv` by default. This can be less reliable than a direct Node.js installation, especially in restricted CI/CD environments or without `bash` availability. For more robust Node.js handling, install with the `nodejs` extra (`pip install pyright[nodejs]`).
fix Use `pip install pyright[nodejs]` for installation. Ensure network access for Node.js download if not already present in PATH.
gotcha When using `pyright-python` with `pre-commit`, it often runs in an isolated virtual environment, which can prevent Pyright from detecting your project's installed dependencies. This leads to 'unknown import' errors.
fix Configure Pyright to explicitly use your project's virtual environment. Add a `[tool.pyright]` section to your `pyproject.toml` or create a `pyrightconfig.json` with `venvPath = "."` and `venv = ".venv"` (adjust `.venv` to your actual virtual environment directory name). Alternatively, configure pre-commit to install your dependencies into its hook environment.
gotcha Manually defining an `exclude` option in `pyrightconfig.json` or `pyproject.toml` *replaces* Pyright's default excluded paths (like `node_modules`, `__pycache__`, virtual environments). Failing to re-include these common exclusions can cause massive slowdowns or hangs as Pyright attempts to analyze irrelevant files.
fix Always explicitly include common exclusion paths (e.g., `node_modules`, `__pycache__`, your virtual environment directory) when providing a custom `exclude` list in your Pyright configuration.
gotcha Pyright does not support a plugin system, unlike some other type checkers (e.g., MyPy). This means it may not fully understand or correctly type-check code that relies on MyPy-specific plugins (e.g., for complex ORMs like Django or some Pydantic features), potentially leading to false positives or missed errors.
fix Consult Pyright's documentation for its native support for advanced type features. For libraries with known MyPy plugins, verify Pyright's compatibility or consider workarounds like `type: ignore` comments if needed. This may be a reason to use MyPy if deeply integrated with such libraries.
pip install pyright[nodejs]

This quickstart demonstrates how to run Pyright on a simple Python file. The `pyright` Python package primarily provides a command-line executable. Programmatic invocation within Python is typically done by calling the `pyright` command via `subprocess`.

import os

# Create a dummy Python file to check
with open("my_module.py", "w") as f:
    f.write("def greet(name: str) -> int:\n    return f'Hello, {name}'\n\nresult = greet('World')\n")

# Run pyright via the command line (typical usage)
# This is equivalent to `pyright my_module.py` in the terminal
import subprocess

try:
    # Using python -m pyright to ensure the installed package's executable is found
    process = subprocess.run(
        ['python', '-m', 'pyright', 'my_module.py'],
        capture_output=True,
        text=True,
        check=False  # Do not raise an exception for non-zero exit codes
    )
    print("Pyright Output:\n" + process.stdout)
    if process.stderr:
        print("Pyright Errors:\n" + process.stderr)
    if process.returncode != 0:
        print(f"Pyright exited with code {process.returncode}. Errors found.")
    else:
        print("Pyright completed with no errors.")
except FileNotFoundError:
    print("Error: 'pyright' command not found. Ensure pyright is installed and in PATH.")
except Exception as e:
    print(f"An error occurred: {e}")

# Clean up the dummy file
os.remove("my_module.py")