Pyright for 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.
Warnings
- 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]`).
- 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.
- 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.
- 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.
Install
-
pip install pyright -
pip install pyright[nodejs]
Quickstart
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")