pyright icon indicating copy to clipboard operation
pyright copied to clipboard

Pyright does not deduce types that it should

Open acampove opened this issue 5 months ago • 4 comments

Describe the bug

There seem to be cases where the type is obvious, but pyright needs to be explicitly told. This potentially could hide bugs in the user's code.

Code or Screenshots

class Foo:
    bar: list[int]

foo = Foo()

components = foo.bar
components = 3

I see:

(rx_run3) [acampove@thinkbook explicit-annotation]$ pyright test.py
0 errors, 0 warnings, 0 informations
(rx_run3) [acampove@thinkbook explicit-annotation]$ cat pyrightconfig.json
{
  "typeCheckingMode": "strict"
}

Here components could be reasigned incorrectly later.

VS Code extension or command-line Are you running pyright as a VS Code extension, a language server in another editor, integrated into Pylance, or the command-line tool? Which version?

I am using the CLI, but the same problem happens in neovim. The version is:

pyright 1.1.411

acampove avatar Jun 29 '26 01:06 acampove

https://github.com/microsoft/pyright/blob/main/docs/type-concepts.md#type-declarations

If a variable or parameter has no type annotation, Pyright will assume that any value can be assigned to it.

after the first assignment, component has type list[int]; after second assignment, it has type int.

pinterior avatar Jun 29 '26 19:06 pinterior

As @pinterior pointed out. If you don't give a variable a type, Pyright assumes its intended type is Any and allows all assignments to it. Even in strict mode.

I suppose this might be considered an enhancement request to catch these situations? I think that's likely outside the scope of Pyright though and more something like what Ruff would do.

Pyright checks for things that will cause runtime errors but doesn't check for things that are generally considered linting problems.

rchiodo avatar Jun 29 '26 20:06 rchiodo

If a variable or parameter has no type annotation, Pyright will assume that any value can be assigned to it

But pyright knows the type of the value that component is assigned to, so the user should not have to specify it by hand. That is just bad design and will make the user's code less readable. @pinterior @rchiodo

acampove avatar Jul 02 '26 03:07 acampove

This may be your intent though (a variable that changes types). If you want a variable to always have a specific type, then you'd give it a type annotation. Pyright will check that.

rchiodo avatar Jul 02 '26 16:07 rchiodo