profile
viewpoint
Eric Traut erictraut Microsoft Corp. Redmond, WA Eric is a Technical Fellow at Microsoft. He has worked on many projects including HyperV, Windows Core OS, Skype, and AI for Autonomous Systems.

microsoft/pyright 5390

Static type checker for Python

microsoft/ReSub 594

A library for writing React components that automatically manage subscriptions to data sources simply by accessing them

microsoft/NoSQLProvider 85

A cross-browser/platform indexeddb-like client library

microsoft/SyncTasks 33

An explicitly non-A+ Promise library that resolves promises synchronously

BonsaiAI/bonsai-simulink 2

Microsoft Bonsai Simulink Toolbox and sample models

erictraut/bonsaiai.github.io 0

Bonsai's Slate Developer Documentation

erictraut/NoSQLProvider 0

A cross-browser/platform indexeddb-like client library

erictraut/python-language-server 0

Microsoft Language Server for Python

erictraut/TypeScript 0

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

push eventmicrosoft/pyright

Eric Traut

commit sha 794740f21cfc0b3675c577b8d7acef310947ea58

Fixed regression in completion provider when retrieving suggestions for "self.". Added test to cover this case.

view details

push time in 2 hours

issue commentmicrosoft/pylance-release

Pylance doesn't suggest the methods in a class

Thanks for reporting the problem. You are correct, of course. It should suggest methods, properties and instance variables that are appropriate for self.

This is a regression that was introduced recently when we changed the way the type of self is inferred. I've addressed the problem, and the fix will be in an upcoming version of Pylance.

albireox

comment created time in 2 hours

issue commentmicrosoft/pyright

Pyright report typing problems even when using a typed lib

By default, Pyright looks only at type stubs for its type information. If you want it to use library code (".py" files) for type information (regardless of whether there are annotations in that code), you need to enable that feature. If you're using the VS Code extension, you can do this by setting "pyright.useLibraryImplementations" to true. If you're using the command-line version of Pyright, you can use the "--lib" switch. If you do this, the first error will go away because Pyright will be able to determine the type of app from the ".py" file.

In strict mode, every diagnostic rule is enabled. This mode is useful for production code bases where you want to leverage static type checking to find as many bugs as possible, and you don't mind investing the time to make the code "strictly typed". Enabling strict mode for an existing code base (one that wasn't written from scratch with strict enabled) typically requires quite a bit of work. Pyright is designed to allow you to enable strict mode on a file-by-file or directory-by-directory basis, leaving less-important code (e.g. test code or legacy code) alone. I've documented some tips here. You can start also start with "basic" type checking mode and then enable individual diagnostic rules for your code base as you work your way toward "strictly typed".

All diagnostic rules apply only to your code, not the code in libs. The "reportUnknownMemberType" diagnostic, for example, is telling you that your code is accessing a member whose type is unknown. Oftentimes, the preferred way to eliminate an "unknown type" diagnostic message is to augment or fix the type information in a type stub file or the library code.

marlonpatrick

comment created time in 2 hours

issue commentmicrosoft/pyright

Pyright report typing problems even when using a typed lib

This is the expected behavior when you use pyright in "strict" mode.

While the fastapi library contains some type information, it is incomplete. For example, the get method in the FastAPI class returns the type Callable, which doesn't specify the parameters or return type of the callable. Without this additional information, type analysis will be incomplete, leaving you vulnerable to type-related errors.

A correctly-annotated decorator should use a TypeVar that is bound to a Callable type -- something like this.

_TCallable = TypeVar("_TCallable", bound=Callable[..., Any])
def get(...) -> Callable[[_TCallable], _TCallable]: ...

If I add this annotation to the fastapi get method, pyright no longer reports these errors.

If you don't want to see these errors, pyright allows you to use less-strict modes. You can even disable specific errors on a file-by-file basis using comments at the top of the file:

# pyright: reportUnknownVariableType=false, reportUnknownMemberType=false, reportUntypedFunctionDecorator=false
marlonpatrick

comment created time in 5 hours

issue closedmicrosoft/pyright

Diagnostics are not cleared when switching diagnostic mode from "workspace" to "open files only"

Set the diagnostic mode to "workspace" and open a workspace where multiple files contain type errors. Open one such file. Change the diagnostic mode to "open files only".

Expected behavior: all other diagnostics corresponding to non-open files should be cleared from the problems window.

closed time in 6 hours

erictraut

issue commentmicrosoft/pyright

Diagnostics are not cleared when switching diagnostic mode from "workspace" to "open files only"

This is addressed in Pyright 1.1.49, which I just published.

erictraut

comment created time in 6 hours

issue closedmicrosoft/pyright

Pyright cannot resolve the `wandb` module import, although it can resolve every other import.

Describe the bug Pyright cannot resolve the wandb module import, although it can resolve every other import.

To Reproduce I am using poetry, but running pyright directly from the command line (inside the venv) results in the same problem.

  • Start a new venv
  • Import the module wandb in a file, alongside any other installed dependency, say, sklearn
  • Run pyright (or pylance from VSCode)
  • Pyright appropriately resolves the sklearn import, but not wandb
  • Pyright gives the error error: Import "wandb" could not be resolved (reportMissingImports)

Expected behavior Pyright can resolve the wandb import correctly

Screenshots or Code

<details><summary> Log from pyright --verbose</summary> <p>

No configuration file found.
Search paths found for configured python interpreter:
  /usr/lib/python3.8
  /usr/lib/python3.8/lib-dynload
  /home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages
When attempting to get search paths from python interpreter:
  Executing python interpreter
  Skipping '/usr/lib/python38.zip' because it is not a valid directory
  Received 3 paths from interpreter
    /usr/lib/python3.8
    /usr/lib/python3.8/lib-dynload
    /home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages
stubPath /home/italo/dev/tmp/test/test/typings is not a valid directory.
Searching for source files
Found 3 source files
Could not import 'wandb' in file '/home/italo/dev/tmp/test/test/__init__.py'
  Looking for typeshed stdlib path
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3/wandb.py'
  Typeshed path not found
  Looking in root directory of execution environment '/home/italo/dev/tmp/test/test'
  Attempting to resolve using root path '/home/italo/dev/tmp/test/test'
  Partially resolved import with directory '/home/italo/dev/tmp/test/test/wandb'
  Looking in stubPath '/home/italo/dev/tmp/test/test/typings'
  Attempting to resolve using root path '/home/italo/dev/tmp/test/test/typings'
  Did not find file '/home/italo/dev/tmp/test/test/typings/wandb.pyi' or '/home/italo/dev/tmp/test/test/typings/wandb.py'
  Looking for typeshed path
  Looking for typeshed third_party path
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3/wandb.py'
  Typeshed path not found
  Looking in python search path '/usr/lib/python3.8'
  Attempting to resolve using root path '/usr/lib/python3.8'
  Did not find file '/usr/lib/python3.8/wandb.pyi' or '/usr/lib/python3.8/wandb.py'
  Looking in python search path '/usr/lib/python3.8/lib-dynload'
  Attempting to resolve using root path '/usr/lib/python3.8/lib-dynload'
  Did not find file '/usr/lib/python3.8/lib-dynload/wandb.pyi' or '/usr/lib/python3.8/lib-dynload/wandb.py'
  Looking in python search path '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages'
  Attempting to resolve using root path '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages'
  Resolved import with file '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages/wandb/__init__.py'
Could not import 'wandb' in file '/home/italo/dev/tmp/test/test/run.py'
  Looking for typeshed stdlib path
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3/wandb.py'
  Typeshed path not found
  Looking in root directory of execution environment '/home/italo/dev/tmp/test/test'
  Attempting to resolve using root path '/home/italo/dev/tmp/test/test'
  Partially resolved import with directory '/home/italo/dev/tmp/test/test/wandb'
  Looking in stubPath '/home/italo/dev/tmp/test/test/typings'
  Attempting to resolve using root path '/home/italo/dev/tmp/test/test/typings'
  Did not find file '/home/italo/dev/tmp/test/test/typings/wandb.pyi' or '/home/italo/dev/tmp/test/test/typings/wandb.py'
  Looking for typeshed path
  Looking for typeshed third_party path
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3/wandb.py'
  Typeshed path not found
  Looking in python search path '/usr/lib/python3.8'
  Attempting to resolve using root path '/usr/lib/python3.8'
  Did not find file '/usr/lib/python3.8/wandb.pyi' or '/usr/lib/python3.8/wandb.py'
  Looking in python search path '/usr/lib/python3.8/lib-dynload'
  Attempting to resolve using root path '/usr/lib/python3.8/lib-dynload'
  Did not find file '/usr/lib/python3.8/lib-dynload/wandb.pyi' or '/usr/lib/python3.8/lib-dynload/wandb.py'
  Looking in python search path '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages'
  Attempting to resolve using root path '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages'
  Resolved import with file '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages/wandb/__init__.py'
Could not import 'wandb' in file '/home/italo/dev/tmp/test/test/wandb/run-20200703_135936-2ixedkt7/code/run.py'
  Looking for typeshed stdlib path
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.7/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3.6/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/3/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/stdlib/2and3/wandb.py'
  Typeshed path not found
  Looking in root directory of execution environment '/home/italo/dev/tmp/test/test'
  Attempting to resolve using root path '/home/italo/dev/tmp/test/test'
  Partially resolved import with directory '/home/italo/dev/tmp/test/test/wandb'
  Looking in stubPath '/home/italo/dev/tmp/test/test/typings'
  Attempting to resolve using root path '/home/italo/dev/tmp/test/test/typings'
  Did not find file '/home/italo/dev/tmp/test/test/typings/wandb.pyi' or '/home/italo/dev/tmp/test/test/typings/wandb.py'
  Looking for typeshed path
  Looking for typeshed third_party path
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/3/wandb.py'
  Attempting to resolve using root path '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3'
  Did not find file '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3/wandb.pyi' or '/usr/lib/node_modules/pyright/dist/typeshed-fallback/third_party/2and3/wandb.py'
  Typeshed path not found
  Looking in python search path '/usr/lib/python3.8'
  Attempting to resolve using root path '/usr/lib/python3.8'
  Did not find file '/usr/lib/python3.8/wandb.pyi' or '/usr/lib/python3.8/wandb.py'
  Looking in python search path '/usr/lib/python3.8/lib-dynload'
  Attempting to resolve using root path '/usr/lib/python3.8/lib-dynload'
  Did not find file '/usr/lib/python3.8/lib-dynload/wandb.pyi' or '/usr/lib/python3.8/lib-dynload/wandb.py'
  Looking in python search path '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages'
  Attempting to resolve using root path '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages'
  Resolved import with file '/home/italo/.cache/pypoetry/virtualenvs/test-Cf4rN2Qf-py3.8/lib/python3.8/site-packages/wandb/__init__.py'
/home/italo/dev/tmp/test/test/__init__.py
  3:8 - error: Import "wandb" could not be resolved (reportMissingImports)
/home/italo/dev/tmp/test/test/run.py
  2:8 - error: Import "wandb" could not be resolved (reportMissingImports)
/home/italo/dev/tmp/test/test/wandb/run-20200703_135936-2ixedkt7/code/run.py
  2:8 - error: Import "wandb" could not be resolved (reportMissingImports)
3 errors, 0 warnings 
Completed in 0.907sec

</p> </details>

VS Code extension or command-line This happens with Pylance 2020.6.1 and pyright 1.1.48

Additional context What strikes me as odd is that pyright can find the module (Resolved import with file [...]), but for some reason, it still doesn't resolve it.

closed time in 6 hours

oyarsa

issue commentmicrosoft/pyright

Pyright cannot resolve the `wandb` module import, although it can resolve every other import.

This is addressed in Pyright 1.1.49, which I just published.

oyarsa

comment created time in 6 hours

issue closedmicrosoft/pyright

Incorrect reportAssertAlwaysTrue when asserting Tuple[T] not empty

Describe the bug When asserting a Tuple[T] variable as truthy (i.e., nonempty), PyRight reports the assertion always holds. However, a tuple of this type can be the empty tuple and evaluate as false.

This was hit when asserting that at least one value was provided to a varargs function.

To Reproduce

def g():
    x: Tuple[Any] = tuple()
    assert x  # Produces: Assert expression always evaluates to true (reportAssertAlwaysTrue)

g()  # raises AssertionError

Expected behavior This should not report the assert always holds.

The report can be suppressed with an explicit cast to bool, which changes the type of the assert expression away from Tuple.

Screenshots or Code Actual use-case was more like:

def f(*args: int):
    assert args  # Produces: Assert expression always evaluates to true (reportAssertAlwaysTrue)
    ...

f()  # raises AssertionError

VS Code extension or command-line Running from CLI. Version: pyright 1.1.48.

Additional context

I think this occurs because of the logic to detect erroneous multi-line asserts that are actually tuples. The check might need to be scoped down to trigger on specifically an expression of known tuple size two, though I am not sure if this would be fragile.

closed time in 6 hours

NicholasGorski

issue commentmicrosoft/pyright

Incorrect reportAssertAlwaysTrue when asserting Tuple[T] not empty

This is addressed in Pyright 1.1.49, which I just published.

NicholasGorski

comment created time in 6 hours

issue closedmicrosoft/pyright

update typeshed to support redis-py 3.5.x

Describe the bug HMSET is deprecated, and HSET with a mapping arg should be used instead. The currently bundled typeshed stubs don't allow for a mapping kwarg to be passed to hset.

It looks like the update to support this made it into typeshed a couple days ago: https://github.com/python/typeshed/pull/4293

Could you update to the latest version of typeshed in the next release?

To Reproduce

  1. Install redis-py@3.5.3
  2. Attempt to pass a mapping to hset.
  3. See error.

Expected behavior No error.

Screenshots or Code Screen Shot 2020-07-01 at 8 40 56 PM

VS Code extension or command-line Name: Pylance Id: ms-python.vscode-pylance Description: A performant, feature-rich language server for Python in VS Code Version: 2020.6.1 Publisher: Microsoft VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance

Additional context Add any other context about the problem here.

closed time in 6 hours

jaypaik

issue commentmicrosoft/pyright

update typeshed to support redis-py 3.5.x

This is addressed in Pyright 1.1.49, which I just published.

jaypaik

comment created time in 6 hours

issue closedmicrosoft/pyright

Use of "from .x import y" in pyi file should add implicit symbol export of "x"

According to PEP 484:

Just like in normal Python files [importdocs], submodules automatically become exported attributes of their parent module when imported. For example, if the spam package has the following directory structure:

spam/ init.pyi ham.pyi where init.pyi contains a line such as from . import ham or from .ham import Ham, then ham is an exported attribute of spam.

closed time in 6 hours

erictraut

issue commentmicrosoft/pyright

Use of "from .x import y" in pyi file should add implicit symbol export of "x"

This is addressed in Pyright 1.1.49, which I just published.

erictraut

comment created time in 6 hours

issue closedmicrosoft/pyright

DefaultDict inside DefaultDict is not typed correctly

Describe the bug In the following code, pyright reports inappropriate type error in the line 6:

Argument of type "str" cannot be assigned to parameter "k" of type "int" in function "__getitem__"
  "str" is incompatible with "int"Pyright (reportGeneralTypeIssues)

To Reproduce

from typing import DefaultDict

dic = DefaultDict(lambda: DefaultDict(int))
x: int = 1992
y: str = 'p_km'
dic[x][y] += 928

Expected behavior No error.

Screenshots or Code image

VS Code extension or command-line VS Code extension (Pyright 1.1.48, Python (extension) 2020.6.91350, VS Code 1.46.1, Python 3.8.3 64-bit)

Additional context n/a

closed time in 6 hours

kissge

issue commentmicrosoft/pyright

DefaultDict inside DefaultDict is not typed correctly

This is addressed in Pyright 1.1.49, which I just published.

kissge

comment created time in 6 hours

created tagmicrosoft/pyright

tag1.1.49

Static type checker for Python

created time in 6 hours

release microsoft/pyright

1.1.49

released time in 6 hours

push eventmicrosoft/pyright

Eric Traut

commit sha 96cb04bc7d716410e11d3a8a2b6b0f08d5454918

Published 1.1.49

view details

push time in 6 hours

startedmicrosoft/pylance-release

started time in 6 hours

issue commentmicrosoft/pylance-release

reportMissingImports when import a file whose name contains an underscore

Pylance doesn't know which search paths will be used at the time you execute your Python code. You need to tell it. By default, Pylance will assume that the search paths will include the root of the workspace you open. It also automatically adds a subdirectory called "src" if it's present, since it's common practice to place your code within a subdirectory of that name. Any other subdirectories that should be included in the search path must be specified using the "python.analysis.extraPaths" setting.

In your example above, you would want to add the following:

"python.analysis.extraPaths": ["helloworld"]

The reason that "helloworld" is being resolved and "hello_world" is not is that the search paths that you have specified include a directory called "helloworld", and it is being treated as a namespace package.

While investigating your bug report, I did find one bug in Pylance, which I have now fixed. When it detected a namespace package, it was not continuing the scan to find a regular module. The Python spec indicates that regular modules or submodules should be preferred over namespace packages. A fix for this bug will be in the next version of Pylance.

RussellJQA

comment created time in 12 hours

push eventmicrosoft/pyright

Eric Traut

commit sha 3cfb5fc417e6d9352eab9310505ca9e2b33b43f8

Fixed regression in reportAssertAlwaysTrue diagnostic.

view details

Eric Traut

commit sha 082b98fa8c63bc7839d588684f081619ec1135b3

Reverted to previous logic for reportAssertAlwaysTrue.

view details

push time in 12 hours

push eventmicrosoft/pyright

Eric Traut

commit sha d00145dfe26139d1ee8544373b43d0f232c1b6d1

Fixed regression in f-string parsing.

view details

push time in 12 hours

push eventmicrosoft/pyright

Eric Traut

commit sha 29ae3d192b806302db1100443456531c5553b33c

Fixed bug in import resolver where it was not preferring regular package imports over namespace packages.

view details

push time in 13 hours

issue commentmicrosoft/pylance-release

Syntax error for passing kwargs to a function inside fstrings

Thanks for the bug report. Pylance was not correctly handling nested braces within an f-string expression. It is now working. The fix will be in an upcoming release of Pylance.

TotallyNotChase

comment created time in 14 hours

push eventmicrosoft/pyright

Eric Traut

commit sha b96e756c1a07d3f6f141a2a3ff7f10d50e6c72b3

Fixed bug in parsing of f-string expressions that contain nested braces.

view details

push time in 14 hours

issue closedmicrosoft/pyright

field recognition failed

Describe the bug https://github.com/django/django/blob/master/django/utils/datastructures.py#L215

field recognition failed

To Reproduce Steps to reproduce the behavior.

Expected behavior success recognition like pycharm

Screenshots or Code image image

VS Code extension or command-line Are you running pyright as a VS Code extension or a command-line tool? Which version? You can find the version of the VS Code extension by clicking on the Pyright icon in the extensions panel.

Additional context Add any other context about the problem here.

closed time in 14 hours

zhuangzhuang

issue commentmicrosoft/pyright

field recognition failed

This code is using a non-standard pattern to inject a new field into an object instance. There are many ways in a language as dynamic as Python to defeat a static type checker. Adding support for all such non-standard patterns isn't feasible.

zhuangzhuang

comment created time in 14 hours

issue commentmicrosoft/pyright

Add formatter (junit)

The command-line version of Pyright already supports an option for outputting results in JSON format (--outputjson switch). This structured format allows other tools to transform the reported diagnostics in any manner they choose. It should be straightforward to write a script that outputs this in JUnit format or any other format required by your CI system.

yuriy1337

comment created time in 14 hours

push eventmicrosoft/pyright

Eric Traut

commit sha 233f5fbea476d73dc9f535ea50b40e5ddb4656e6

Fixed bug that caused diagnostics for unopened files to remain in "problems" panel after switching diagnostic mode from "workspace" to "open files only".

view details

push time in 14 hours

issue commentmicrosoft/pyright

"from pylab import *" break right type

I switched from pylab-sdk to mayplotlib, and I am still unable to repro the problem. Perhaps you're using an older version of matplotlib? Which version do you have installed?

zhuangzhuang

comment created time in 14 hours

issue commentmicrosoft/pyright

Pyright cannot resolve the `wandb` module import, although it can resolve every other import.

Thanks for the additional clues. This is a bug in Pyright's import resolution code. It should always favor a third-party library import if a local import can't be found. A fix will be included in the next version of Pyright.

oyarsa

comment created time in 14 hours

push eventmicrosoft/pyright

Eric Traut

commit sha 51de4f55a4ce470e504880f8b2791aa8f554d6f9

Fixed bug in import resolution that resulted in an unresolved import when a local folder was present with the same name as the imported third-party library.

view details

push time in 14 hours

issue commentmicrosoft/pyright

Incorrect reportAssertAlwaysTrue when asserting Tuple[T] not empty

Digging into this a bit more, I think that bug #1 isn't actually a bug. It's a side effect of the way the __new__ method for the tuple class is defined in the builtins.pyi stub file.

#2 is definitely a bug, and I've introduced a fix. It will be included in the next version of Pyright.

NicholasGorski

comment created time in 14 hours

push eventmicrosoft/pyright

Eric Traut

commit sha f7e260ec48d9b4a945c979ddd525ca1b4987118e

Fixed bug in reportAssertAlwaysTrue diagnostic. It wasn't properly handling tuples of indeterminate length.

view details

push time in 14 hours

issue closedmicrosoft/pyright

Incorrect unreachable code detection after return in `contextlib.suppress`

Describe the bug if there is a return statement in a with contextlib.suppress(Exception) block, then all the code after is grayed out as unreachable.

To Reproduce See the code example below

Expected behavior Code after a return in a contextlib.suppress is not marked as unreachable.

Screenshots or Code

import contextlib
from typing import NoReturn

def func() -> int:
    with contextlib.suppress(KeyError):
        return func2()

    return 5  # this line is grayed out

def func2() -> NoReturn:
    raise KeyError

Screen Shot 2020-06-25 at 2 34 14 PM

Screen Shot 2020-06-25 at 2 36 10 PM

VS Code extension or command-line pyright vscode extension version 1.1.45

closed time in 15 hours

jacobbogdanov

issue commentmicrosoft/pyright

Incorrect unreachable code detection after return in `contextlib.suppress`

As per discussion in this PR thread (https://github.com/microsoft/pyright/pull/771), I'm going to close this for now. Fixing it will add significant complexity to the code, and I'm reluctant to fix it given that 1) assuming behavior of the context manager based on its __exit__ method return type is not part of the Python spec, and 2) there's already a well-defined way in the language to catch exceptions (namely, try/except blocks).

jacobbogdanov

comment created time in 15 hours

issue commentmicrosoft/pyright

DefaultDict inside DefaultDict is not typed correctly

Thanks for the bug report. This will be fixed in the next version.

kissge

comment created time in 15 hours

push eventmicrosoft/pyright

Eric Traut

commit sha 4b9d2d0cf9471f6fae5486702e7e1363451f8c50

Changed constructor type analysis logic to always specialize the instantiated instance.

view details

push time in 15 hours

issue commentmicrosoft/pylance-release

How to disable "Missing Argument" and "Code is unreachable" warnings?

If it's in a third-party library, the recommended way to handle it is through a type stub that defines the interface to that library. If a type stub isn't available, you have the option of creating one yourself. Or you can wait for someone else (perhaps the library's author) to publish a type stub. You can suppress the error in the meantime using a # type: ignore comment, as you pointed out.

HMaker

comment created time in a day

issue commentmicrosoft/pylance-release

How to disable "Missing Argument" and "Code is unreachable" warnings?

You can eliminate the first warning by adding appropriate type annotations to your decorator.

from typing import TypeVar

_T = TypeVar("_T")

class DecoratorClass:
    @classmethod
    def decorator(cls, func: _T) -> _T:
        def wrapper():
            print("Hello from decorator")
            func()

        return wrapper

For the second one, there are two ways you can improve your code an eliminate the warning.

The first way is to declare Superclass as an abstract base class (ABC) and the hello as an abstract method.

from abc import ABC, abstractmethod

class Superclass(ABC):
    @abstractmethod
    def hello(self):
        raise NotImplementedError

The second way is provide an explicit return type annotation for hello so Pylance doesn't need to infer the return type from the code.

class Superclass:
    def hello(self) -> None:
        raise NotImplementedError
HMaker

comment created time in a day

pull request commentmicrosoft/pyright

Improve type inference of context manager that swallow exceptions

Yeah, I think a similar approach might work, but that will involve a bunch of extra code that needs to be written, tested, and maintained. The question in my mind is whether all of that extra special-case code is worth it for this functionality. It's a pretty esoteric feature. You're the first person to report it. If this were an official part of the Python spec, then I wouldn't hesitate to support it, but it's not. So my inclination at this point is to say that it's not worth the extra code. Especially given that this is a non-standard way to handle exceptions when the language already has a perfectly good standard way to handle exceptions — a try/except statement. So my inclination at this point is to not address this issue unless/until the Python spec is updated to indicate that the return type of __exit__ has a special meaning.

jacobbogdanov

comment created time in a day

issue commentmicrosoft/pylance-release

Walrus operator not recognised

Thanks for the bug report. I've fixed the bug, and the fix will be in an upcoming version of Pylance.

ciaranjudge

comment created time in a day

push eventmicrosoft/pyright

Eric Traut

commit sha ef648395dca51519a5440feac34101a755fd26fc

Fixed bug in parser that generated a spurious error when an unparenthesized assignment expression (walrus operator) was used as an argument. PEP 572 indicates that this should be allowed in cases where the argument is not named.

view details

push time in a day

issue commentmicrosoft/pyright

Pyright cannot resolve the `wandb` module import, although it can resolve every other import.

Thanks for the bug report.

I'm not able to repro the problem as described. Perhaps there are additional details. What form of an import statement are you using in your code? Are you using import wandb or from wandb import x?

Here's what I see when I try to repro:

Screen Shot 2020-07-03 at 10 27 20 AM

oyarsa

comment created time in a day

push eventmicrosoft/pyright

Eric Traut

commit sha 3bf7e935227f8fa224e053a758ddcd99563eaf84

Fixed bug in pyrightconfig schema. The defaults for several settings were using strings "true" and "false" rather than booleans true and false.

view details

push time in a day

issue openedmicrosoft/pyright

Diagnostics are not cleared when switching diagnostic mode from "workspace" to "open files only"

Set the diagnostic mode to "workspace" and open a workspace where multiple files contain type errors. Open one such file. Change the diagnostic mode to "open files only".

Expected behavior: all other diagnostics corresponding to non-open files should be cleared from the problems window.

created time in a day

issue commentmicrosoft/pyright

pyproject.toml support

As I said, I'm not interested in supporting another configuration mechanism. Pyright already supports multiple config mechanisms, and the code involved is already very complicated because it needs to deal with precedence between these different mechanisms. Adding yet another will make the code more difficult to maintain.

nihaals

comment created time in a day

issue commentmicrosoft/pylance-release

Auto-import doesn't work

Thanks for the input. I agree that the auto-import behavior is confusing, and there are opportunities to improve it further.

It tends to work better if you set the diagnostic mode to tell pylance to analyze all of the files in your workspace rather than just the open files.

"python.analysis.diagnosticMode": "workspace"

I also like the idea of providing additional documentation for Pylance. In the meantime, the Pyright site may provide you with some of the information you're looking for. Pylance is built on Pyright, so most of the functionality is the same.

imankulov

comment created time in a day

issue commentmicrosoft/pyright

"from pylab import *" break right type

Thanks for the bug report. I'm not able to repro the problem you're seeing. Perhaps there are additional repro steps that I'm missing. I installed the latest versions of pylab-sdk and Pillow.

image

Based on the screen shots you provided, my best guess is that pylab is exporting a symbol called Image, and it is being imported as part of your wildcard import. (Incidentally, using wildcard imports is a very dangerous practice that leads to very fragile code. I highly recommend against ever using wildcard imports.)

zhuangzhuang

comment created time in a day

issue commentmicrosoft/pylance-release

"Arguments missing" for optional arguments

It sounds like your type stub file (pyplot.pyi) contains a bug. Where did you get that stub? I don't see it included in the matplotlib package, nor do I see it in typeshed. In any case, the correct fix here is to fix the bug in the type stub file.

onnoeberhard

comment created time in a day

issue commentmicrosoft/pylance-release

Use of cmp builtin function results in "is not defined" warning

The cmp function exists only in Python 2. It was deprecated in Python 3.

Pylance works only with Python 3. If you want language support for Python 2, you can use the JEDI language server.

rtkapiper

comment created time in a day

issue commentmicrosoft/pylance-release

Problems raised about missing argument when calling a function decorated by celery.shared_task

Pylance requires type stubs to do the best job possibly with type analysis. In this case, I'm presuming that you don't have a type stub available for celery, so it is doing its best to infer types from the library implementation based on the return type(s) of shared_task. In this particular case, shared_task returns two different types, and the type checker can't tell which one is returned for this particular call site. Both types are functions, but one of them is a function that requires a parameter called fun, hence the error.

The best workaround in this case is to find (or create) a type stub for the celery package. A type stub will provide the proper annotations so the type checker can perform analysis correctly in this case without emitting an error.

If you can't find a type stub and don't want to create one, you can suppress this error using "# type: ignore".

remihuguet

comment created time in a day

issue commentmicrosoft/pylance-release

Variable possibly unbound warning after enumerate?

Yes, this is a valid warning. In general a for loop can execute zero (or more) times depending on the iterator provided by the expression after the keyword in. If it executes zero times, the variable i will be unbound, and the program will crash. In this particular case, you know that the iterable enumerate(range(1, 11)) will always cause the for loop to execute more than zero times, but a type checker doesn't have enough information to determine that from the type information it is provided. It must assume this is a possible bug.

If you want to use the target of a for loop (in your case, i) outside of the for loop, you should make sure it is initialized before the for loop. For example:

i = None
TotallyNotChase

comment created time in a day

issue commentmicrosoft/pyright

Incorrect reportAssertAlwaysTrue when asserting Tuple[T] not empty

I think there are a couple of bugs here, but it's not the one you reported.

The type annotation Tuple[Any] indicates that there is a tuple with a single element that is of type Any. This will always evaluate to truthy. If you want to indicate a tuple that is truly empty (zero elements), you would need to use the annotation Tuple[()]. And if you want to indicate that the tuple is of indeterminate length, you would need to use the annotation Tuple[Any, ...].

As I said above, there are a couple of bugs:

  1. If you change your annotation to Tuple[()], Pyright indicates that tuple() cannot be assigned to it.
  2. If you change your annotation to Tuple[Any, ...], Pyright still insists that the assert is unnecessary, when it's possible for the value to be truthy or falsy depending on the number of elements.
NicholasGorski

comment created time in 2 days

issue commentmicrosoft/pylance-release

JSON config does not recognize Pylance as language server

For now, add Pylance as language server and ignore the warning. Otherwise, it won't work.

kovalensue

comment created time in 2 days

issue commentmicrosoft/pyright

Use of "from .x import y" in pyi file should add implicit symbol export of "x"

@federicobond, this is now addressed, and the fix will be in the next version of Pyright and Pylance. Thanks again for reporting the problem.

erictraut

comment created time in 2 days

push eventmicrosoft/pyright

Eric Traut

commit sha c5b9355aec8e145823cb1f3a6ae9080d6515998e

Fixed regression from previous change that caused internal errors when a function was declared in an unreachable suite.

view details

Eric Traut

commit sha f0bc55bedaf808b1cece848569c6fc44e83a6bb8

Added code to include a symbol in a module if the source file is an "__init__.py(i)" and a relative import of the form "from .x.y.z import X" is used. In this case, the symbol "x" should appear within the module's namespace.

view details

push time in 2 days

issue commentmicrosoft/pylance-release

Code is marked as unreachable, even though it isn't

Thanks for the bug report. I've fixed the issue, and it will be addressed in a future release of Pylance.

max-wittig

comment created time in 2 days

push eventmicrosoft/pyright

Eric Traut

commit sha ae491f49084baaeb9065b79e192f4b4aabb51889

Fixed bug in unreachable code detection and reporting. The logic was previously split between the binder (which used proper code flow analysis) and the checker (which didn't use code flow analysis but had access to NoReturn call information). The new code combines everything into the checker and uses both code flow analysis and NoReturn call info.

view details

push time in 2 days

issue commentmicrosoft/pylance-release

Make possible to use pylance with a local fork of pyright

@r3m0t, can you provide more details about why you want to use pylance with a local fork of pyright? What is the use case you have in mind? This can help us explore potential solutions that meet your needs.

savannahostrowski

comment created time in 2 days

issue commentmicrosoft/python-language-server

Platform-Specific Imports - Ignore 'Unresolved Import' for specific package

One option is to replace the f.is_mac() and f.is_win() calls with sys.platform == 'darwin' and sys.platform == 'win32' respectively. Pylance will recognize these built-in conditional checks and analyze only the portions of the code that apply to your current platform.

jaymegordo

comment created time in 2 days

issue commentmicrosoft/pylance-release

wrong "overload is not iterable" error

@gramster, this looks like a bug in the pandas type stubs. The values methods are not marked with @property. Also, it looks like you were trying to use an @overload decorator for the values property getter, but @overload works only with functions, and a property is an object, so you unfortunately can't overload a property.

geepy

comment created time in 2 days

issue commentmicrosoft/pylance-release

Quiet import error if import is wrapped in an import error exception handler

This is intended behavior. You are correct that import statements can be included within try/except blocks or within conditional statements, but they are still import statements, and there is utility in being told when the import cannot be resolved. If you want to suppress this error message, you have a couple of options:

  1. Disable that particular diagnostic for the file by adding a comment at the top:
# pyright: reportMissingModuleSource=false
  1. Suppress the diagnostic for that particular line by adding a comment at the end of the line:
# type: ignore
rswdp

comment created time in 2 days

issue closedmicrosoft/pyright

Operator "+" not supported for types "list[Tuple[Literal[''], Literal['foo']]]" and "list[Tuple[Literal['bar'], Literal['baz']]]"

The following code fails to typecheck:

[('', 'foo')] + [('bar', 'baz')]

It gives the error:

Operator "+" not supported for types "list[Tuple[Literal[''], Literal['foo']]]" and "list[Tuple[Literal['bar'], Literal['baz']]]"

I am running Pyright in VS Code. Might be a similar case to https://github.com/microsoft/pyright/issues/441

closed time in 3 days

federicobond

issue commentmicrosoft/pyright

update typeshed to support redis-py 3.5.x

I've updated typeshed stubs to the latest found in the typeshed repos. This will be included in the next release of pyright.

jaypaik

comment created time in 3 days

push eventmicrosoft/pyright

Eric Traut

commit sha a5f8f5ac579aa5fced3af0636efc639d974d9077

Improved error message for overloaded calls where no overload matches the provided arguments.

view details

push time in 3 days

issue commentmicrosoft/pylance-release

spurious error using pytorch Tensor.item()

Type annotations don't perform type coercion or casting. They declare the type of a symbol. In this case, the type annotation that you added ("# type: int") indicates that the type of x is an int. You are attempting to assign a value that is of type Union[int, float, bool] to an int, hence the type error.

Incidentally, I wouldn't recommend using type comments unless you need to maintain backward compatibility with Python 3.5 or earlier. As of Python 3.6, variables can be annotated using a more readable syntax like this:

x: int = t.item()

The method Tensor.item is annotated to return a value of type Union[int, float, bool]. I don't know much about pytorch, so I can't say for sure whether this is correct or a bug in the type stub. I'm surprised to see that the Tensor class is not a generic class. Perhaps that's the problem here. Since it's not generic, the authors of this type stub assume that it supports elements that are int, float or bool.

There are a couple of workarounds here:

  1. Use an assert.
x = t.item()
assert isinstance(x, int)
  1. Use a cast.
x = cast(int, t.item())

I almost always prefer asserts over casts since the former affords a level of runtime validation. I tend to use casts only as a last resort because they disable all type checking.

joelgrus

comment created time in 3 days

issue commentmicrosoft/pylance-release

if/elif/else statement need better error handling

There are two issues here.

The first is that we were not doing a better job with parse recovery once a parse error is detected. Your example code resulted in about eight different errors. I've improved the parse recovery in this case to avoid the cascading errors. With my improvements, you will now see only two error messages.

The second issue is with the error message. I disagree that "syntax error" is a better message. This is a very generic term, and many beginning Python users won't even know what "syntax error" means. Good error messages are understandable, specific, and provide the user with information about what was expected or what they can do to fix it. As such, I think the current error message is an appropriate and useful message.

Rabbit994

comment created time in 3 days

push eventmicrosoft/pyright

Eric Traut

commit sha ad9ef6625c1a63c86f213d753e6fa587697a428f

Improved parse recovery for statements that are supposed to end in a colon followed by a suite of other indented statements. Previously, a missing colon or expression error resulted in a cascade of additional errors.

view details

push time in 3 days

issue commentmicrosoft/pylance-release

Spurious error when Unicode character names used in f-string

Thanks for the bug report. This isn't related to f-strings specifically. It affects other string literals too. Pyright/pylance is not properly handling escaped unicode names that contain spaces. I've fixed the problem, and it will be addressed in the next version of pyright/pylance.

t1m0thyj

comment created time in 3 days

push eventmicrosoft/pyright

Eric Traut

commit sha 09072d673b3041d9b457353e31c28fab6c15f568

Fixed bug in tokenizer where it was generating an error if escaped unicode characters (using the \N{name} escape) contained a space in the name.

view details

push time in 3 days

push eventmicrosoft/pyright

Eric Traut

commit sha c71c7b68d8b970f225ef8b5a4c99bc8dc1497fd0

Updated typeshed stubs to the latest versions from the typeshed repo.

view details

push time in 3 days

issue commentmicrosoft/pyright

Operator "+" not supported for types "list[Tuple[Literal[''], Literal['foo']]]" and "list[Tuple[Literal['bar'], Literal['baz']]]"

This is intended behavior.

When Pyright sees the expression ('', 'foo'), it needs to infer its type if there is no annotation provided. The following types would arguably be valid for this expression:

Tuple[Literal[''], Literal['foo']]
Tuple[str, str]
Tuple[str, ...]
Tuple[Any, ...]

I've listed those in order of specific to general. Without additional guidance from an annotation, Pyright uses heuristics to infer the type. In the case of tuples, it uses the most specific type possible, since that generally provides the best type safety.

Similarly, when Pyright encounters a list expression (e.g. [1, "hi"] or [3.4, 2.3]) without any type annotation, it needs to infer the type. In the case of lists, it uses the following heuristic:

  1. If all of the elements in the list are the same type T, assume the type of the list is List[T].
  2. If the element types don't match and the strictListInference configuration setting is set to true, assume the type of the list is List[Union[A, B, C, ...]].
  3. If strictListInference is false (which it is by default), assume the type of the list is List[Any].

Applying these rules to your example: The type of expression ('', 'foo') is Tuple[Literal[''], Literal['foo']] The type of expression [('', 'foo')] isList[Tuple[Literal[''], Literal['foo']]]Similarly, the type of expression[('bar', 'baz')]isList[Tuple[Literal['bar'], Literal['baz']]If you attempt to add these together, theaddmethod on thelist` class indicates that there is a type violation because the types of the lists don't match.

The correct workaround in this case is to do the following:

StringListTuple = List[Tuple[str, str]]
a: StringListTuple = [('', 'foo')]
a + [('bar', 'baz')]

Note that I've created a type alias StringListTuple for convenience here.

federicobond

comment created time in 3 days

issue commentmicrosoft/pylance-release

*args type checking

I found and fixed the bug and added some additional unit tests. It will be fixed in the next release. Thanks again for the bug report.

max-sixty

comment created time in 3 days

push eventmicrosoft/pyright

Eric Traut

commit sha 20fac0da05c68caa50caba7feb9ff44261d428cc

Fixed bug that caused incorrect type to be determined for *args and **kwargs parameters in some contexts.

view details

push time in 3 days

issue commentmicrosoft/pylance-release

*args type checking

This is definitely a bug in pyright/pylance. I'm debugging it now. In some code path (not yet determined) it's not treating the type of args as a Tuple. In other code paths it does. Stay tuned for a fix. And thanks for reporting the problem.

max-sixty

comment created time in 3 days

issue commentmicrosoft/pylance-release

pd.DataFrame not in completion results

Is this perhaps related to this bug? https://github.com/microsoft/pyright/issues/782

qubitron

comment created time in 3 days

issue commentmicrosoft/pylance-release

Issues when `str` is defined as a class variable

@jakebaily, if you're within the class, you don't need to use the class name to refer to the class variable. For example, this runs fine and prints "3".

class Foo:
    str = 3
    str2 = str
    print(str2)
max-sixty

comment created time in 3 days

issue commentmicrosoft/python-language-server

Undefined variable: 'str' as part of correct type annotation

Type annotations do not follow code flow order when an annotation symbol is resolved. They support forward declarations.

Here are two options for how to work around this in your code:

  1. Don't redefine str in your code. This is the preferable solution, since redefining built-in symbols is a bad practice in general and can lead to significant confusion and fragility in your code.
  2. If option 1 doesn't work for some reason, define an alias to str in your code using a type alias and use that alias within your type annotations. Type aliases do follow code flow rules, so if you put this at the top of your file, the type alias will be defined in terms of the built-in str. Here's how that might look:
buitin_str = str
x: builtin_str = "hi"

I realize that mypy may allow you to get away with redeclaring a built-in symbol at the end of the file, but Pylint/Pyright don't because of the lazy evaluation design that gives them their fast performance. I'll also point out that mypy will likely need to change their behavior for Python 3.9 because of this new language feature: Postponed Evaluation of Type Annotations.

max-sixty

comment created time in 3 days

issue openedmicrosoft/pyright

Use of "from . import x" or "from .x import y" in pyi file should add implicit symbol export

According to PEP 484:

Just like in normal Python files [importdocs], submodules automatically become exported attributes of their parent module when imported. For example, if the spam package has the following directory structure:

spam/ init.pyi ham.pyi where init.pyi contains a line such as from . import ham or from .ham import Ham, then ham is an exported attribute of spam.

created time in 3 days

pull request commentpython/typeshed

Add exports for json.decoder and json.encoder

Ah, interesting. Thanks for that reference. I missed that part in PEP 484. I think it's unfortunate that it's defined this way. In my opinion, stub authors should need to be explicit about what symbols are exported from a module. But if that's what the spec says, I'll update Pyright to honor it.

federicobond

comment created time in 3 days

pull request commentpython/typeshed

Add exports for json.decoder and json.encoder

By my reading of the standards, the current json type stubs allows the following two variations:

import json
json.JSONDecodeError

and

import json.decoder
json.decoder.JSONDecodeError

But the following should produce a type-checking error:

import json
json.decoder.JSONDecodeError

If you think that that last code snippet should not emit an error, could you explain why? There's nothing in the json/__init__.pyi type stub that indicates that it exports the symbol decoder.

federicobond

comment created time in 3 days

issue closedmicrosoft/pyright

Modules in symlinked directories cannot be resolved

Describe the bug A clear and concise description of what the bug is. importing modules from symlinked subdirectories causes [Pyright (reportMissingImports)]

VS Code extension or command-line Running pyright with macos on neovim with coc-pyright on MacOS

closed time in 4 days

robertocarta

issue commentmicrosoft/pyright

Modules in symlinked directories cannot be resolved

Closing for now, since I don't have enough information to repro. I'm happy to re-open it if more details are provided.

robertocarta

comment created time in 4 days

issue closedmicrosoft/pyright

Pyright doesn't recognize the `__members__` attribute of enumeration class

Describe the bug According to Python official document (https://docs.python.org/3.8/library/enum.html#iteration), there is an attribute __members__ of every enumeration class that provides all names defined in the enumeration class. Since it appears in the official document, we should consider it a public API. But Pyright doesn't seem to recognize the __members__ attribute, as elaborated in the following screenshot.

To Reproduce

from enum import Enum

class Fruit(Enum):
    apple = 1
    orange = 2
    pear = 3

print(Fruit.__members__)

Expected behavior Pyright should be able to recoginize __members__ as a mapping.

Screenshots or Code image image

VS Code extension or command-line Pyright is run as VS Code extension. Extension version 1.1.44

closed time in 4 days

MapleCCC

issue commentmicrosoft/pyright

Pyright doesn't recognize the `__members__` attribute of enumeration class

This is now fixed in Pyright version 1.1.48, which I just published. It will also be included in the next public release of Pylance.

MapleCCC

comment created time in 4 days

issue closedmicrosoft/pyright

Report variables that not being assigned any value at all.

Is your feature request related to a problem? Please describe. The current version of Pyright won't report unassigned variables as long as they have a type annotation. Please see the screenshot. image image

Variable a in fn1 and variable b in fn2 can both lead to runtime error local variable X referenced before assignment, but only the second one is being reported by Pyright now.

Describe the solution you'd like I think a in fn1 should also be reported as an error (not sure what kind of error though) because there will be a runtime error.

Additional context Thanks!

Codes:

def fn1():
    a: int
    return a

fn1()

def fn2():
    b
    return b

fn2()

closed time in 4 days

giyyapan

issue commentmicrosoft/pyright

Report variables that not being assigned any value at all.

This is now fixed in Pyright version 1.1.48, which I just published. It will also be included in the next public release of Pylance.

giyyapan

comment created time in 4 days

issue commentmicrosoft/pyright

Missing type narrowing of self

This is now fixed in Pyright version 1.1.48, which I just published. It will also be included in the next public release of Pylance.

jacobbogdanov

comment created time in 4 days

issue closedmicrosoft/pyright

Missing type narrowing of self

Describe the bug Pyright does not correctly narrow the type of self based on isinstance guard clause.

To Reproduce See code below.

Expected behavior adding isinstance(self, X) should narrow the type of self to only be X within that scope.

Screenshots or Code

class Base:
    def get_value(self) -> int:
        if isinstance(self, Derived):
            return self.calculate()  # Cannot access member "calculate" for type "Base"
                                     # Member "calculate" is unknown
        return 7

class Derived(Base):
    def calculate(self) -> int:
        return 2 * 2

Interestingly enough, adding almost any type annotation to self in the function signature causes this error to go away. so

  • def get_value(self: Base) -> int:
  • def get_value(self: Union[Base, "Derived"]) -> int:
  • def get_value(self: Any) -> int: all resolve the issue.

VS Code extension or command-line pyright CLI and vscode extension version 1.1.47

Additional context Add any other context about the problem here.

closed time in 4 days

jacobbogdanov

issue closedmicrosoft/pyright

Awaited task created by `asyncio.create_task()` labeled as not accessed.

Describe the bug Awaited task created by asyncio.create_task() labeled as not accessed.

To Reproduce Steps to reproduce the behavior.

Consider this piece of code:

import asyncio


async def foo() -> None:
    while True:
        await asyncio.sleep(1)
        print("still working")


async def main():
    foo_task = asyncio.create_task(foo())
    await foo_task


asyncio.run(main())

Hovering over foo_task produces the following error: "foo_task" is not accessed

Expected behavior There should be no errors.

Additional context

  • VS Code extension: - 1.1.47
    • settings:
      	{
      		"pyright.typeCheckingMode": "strict",
      		"pyright.useLibraryCodeForTypes": true
      	}
      
  • Python: 3.8.3

closed time in 4 days

pawelrubin

issue commentmicrosoft/pyright

Awaited task created by `asyncio.create_task()` labeled as not accessed.

This is now fixed in Pyright version 1.1.48, which I just published. It will also be included in the next public release of Pylance.

pawelrubin

comment created time in 4 days

issue closedmicrosoft/pyright

Tuple unpacking in return statement with parentheses causes error in Python <3.8

Describe the bug In the VS Code extension using Python 3.7 (Windows 10). When unpacking one tuple into another in a return statement (as in test1 and test2 below), PyRight displays an error

Unpack operation not allowed in tuples prior to Python 3.8

regardless of whether the created tuple is wrapped in parentheses or not. In test2, this error is correct, this is not allowed before Python 3.8. However, in test1, a tuple is created via normal tuple unpacking syntax, which has been allowed since Python 3.5.

To Reproduce

def test1():
    a = [1, 2, 3]
    b = (4, *a, 5)  # This shows no error, as expected
    return (4, *b, 5)  # This causes an error, incorrectly


def test2():
    a = [1, 2, 3]
    return 4, *a, 5  # Here the error is correct

Expected behavior In test2, the error should be displayed for Python <3.8, but not in test which should be allowed for Python >=3.5.

VS Code extension or command-line VS Code extension

Additional context

  • Python 3.7.4
  • PyRight VS Code extension v1.1.47
  • VS Code 1.46.1
  • Windows 10 Pro 1909, 64 bit

closed time in 4 days

MattiasOlla

issue commentmicrosoft/pyright

Tuple unpacking in return statement with parentheses causes error in Python <3.8

This is now fixed in Pyright version 1.1.48, which I just published. It will also be included in the next public release of Pylance.

MattiasOlla

comment created time in 4 days

created tagmicrosoft/pyright

tag1.1.48

Static type checker for Python

created time in 4 days

release microsoft/pyright

1.1.48

released time in 4 days

push eventmicrosoft/pyright

Eric Traut

commit sha c5a22feb75021100624edcee262931718815c555

Published 1.1.48

view details

push time in 4 days

issue commentmicrosoft/pyright

pyright reports possibly a wrong "not a known member of module problem"

If the import os.path statement is successful in resolving the import, it guarantees that there is a local symbol called os that has a valid attribute called path. It doesn't guarantee that the os symbol has any other attributes (such as makedirs). The way that Python resolves the os.path import at runtime happens to also load the os module and fill in these attributes, but you shouldn't rely on this side effect. Pyright intentionally models only the explicit import behaviors, not any of the side effects. In some cases (although not in this particular example), import side effects can even depend on the import resolution ordering, which can change as you add or reorder import statements.

jugmac00

comment created time in 4 days

more