pythonpylancepyright

Replicate Pylance analysis in Pyright


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?


Solution

  • Use basedpyright

    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:

    basedpyright solves this by being both:

    They both use the package installed in the environment and the config in pyproject.toml, so they always report the same errors.

    Switching to basedpyright from Pylance + Pyright

    1. Install basedpyright in your virtual environment, and configure your CI pipeline to use it

    2. Install the basedpyright VS Code extension

    3. Disable Pylance

    4. 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.