I've configured my VS Code project to use the Pylance extension. I know that Pylance is using Pyright internally.
We have a "no-warning" policy. I want to enforce this by running Pyright (in pre-commit and in the CI pipeline). Since Pyright is used internally by Pylance, I figured I should be able to run an equivalent analysis with a standalone Pyright.
My problem is that I don't know how to replicate the Pylance analysis in Pyright. They seem to disagree even if I use the same value for the typeCheckingMode
parameter (i.e. strict
).
For this code:
from typing import Any
a: str = 12345
b: dict[str, Any] = {}
c = b.get("a", {}).get("b", [])
Pylance only spots the first problem:
Expression of type "Literal[12345]" cannot be assigned to declared type "str"
"Literal[12345]" is incompatible with "str"
However, running Pyright on the command-line, I get an additional error:
test.py
test.py:3:10 - error: Expression of type "Literal[12345]" cannot be assigned to declared type "str"
"Literal[12345]" is incompatible with "str" (reportGeneralTypeIssues)
test.py:6:1 - error: Type of "c" is partially unknown
Type of "c" is "Any | list[Unknown]" (reportUnknownVariableType)
2 errors, 0 warnings, 0 informations
I'm wondering:
But the real question is: how can I validate, outside of VS Code, that we don't have any type error in the code that are reported by Pylance?
Pylance is configured differently from Pyright, and they ship with different stubs for libraries, which makes it hard to get them to behave the same way. See:
Pyright and Pylance Together (docs)
Pylance and Pyright CLI does not have the same output (discussion)
basedpyright solves this by being both:
A fork of Pyright (command line tool)
A replacement for Pylance (extension)
They both use the package installed in the environment and the config in pyproject.toml
, so they always report the same errors.
Install basedpyright
in your virtual environment, and configure your CI pipeline to use it
Install the basedpyright VS Code extension
Disable Pylance
Install the stubs that would have been provided by Pylance. Many of them are available in PyPI, such as pandas-stubs and scipy-stubs. The others should be available from microsoft/python-type-stubs.