Giter Site home page Giter Site logo

pyright's Introduction

Pyright

Static Type Checker for Python

Pyright is a full-featured, standards-based static type checker for Python. It is designed for high performance and can be used with large Python source bases.

Pyright includes both a command-line tool and an extension for Visual Studio Code.

Pyright Playground

Try Pyright in your browser using the Pyright Playground.

Documentation

Refer to the documentation for installation, configuration, and usage details.

Community

Do you have questions about Pyright or Python type annotations in general? Post your questions in the discussion section.

If you would like to report a bug or request an enhancement, file a new issue in either the pyright or pylance-release issue tracker. In general, core type checking functionality is associated with Pyright while language service functionality is associated with Pylance, but the same contributors monitor both repos. For best results, provide the information requested in the issue template.

Contributing

This project welcomes contributions and suggestions. For feature and complex bug fix contributions, it is recommended that you first discuss the proposed change with Pyright’s maintainers before submitting the pull request. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

pyright's People

Contributors

ashb avatar bangseongbeom avatar bschnurr avatar cclauss avatar cdce8p avatar christopher-hesse avatar debonte avatar dependabot[bot] avatar erictraut avatar fannheyward avatar heejaechang avatar higoshi avatar insyncwithfoo avatar jakebailey avatar jellezijlstra avatar kinow avatar ljw1004 avatar mhzed avatar microsoftopensource avatar msfterictraut avatar nihaals avatar pylancebot avatar qubitron avatar rchiodo avatar robertcraigie avatar shwetago avatar thetriplev avatar tonybaloney avatar vemel avatar zeronone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyright's Issues

-v does not appear to be respected

This small script creates a virtual environment, installs requests, and then shows that pyright complains that 'requests' could not be resolved:

#!/bin/bash

virtualenv env
source env/bin/activate
pip3 install requests

cat > test.py <<EOF
import requests
EOF

pyright -v env test.py

Output:

Finding source files
Found 1 source files
Analyzed 1 file in 1.414sec
/home/john/test/test.py
  Import 'requests' could not be resolved (1, 8)
1 error, 0 warnings

I could be using -v incorrectly (the documentation is a little unclear), but this usage seems like the most natural by far. Giving garbage paths to -v also does not trigger an error, leading me to believe it just isn't used?

Stuck at 100% CPU when analyzing SciPy 1.2.1

Describe the bug
Pyright (1.0.9) gets stuck on 100% CPU when analyzing SciPy 1.2.1 package.

To Reproduce
Procedure 1:

npm i -g pyright
cd <scipy_1.2.1_site_package_path>
pyright .

Procedure 2:
Create a pipenv project, and

pipenv install scipy

Open project in VsCode. Import scipy in a python file.

import scipy.stats

F12 or 'go to definition' to trigger pyright analysis.
In OSX Activity monitor, "Code Helper" CPU usage stays at 90+%.

Expected behavior
Pyright stops with analysis results.

Screenshots or Code
See above.

VS Code extension or command-line
Both command line and plugin.

Additional context

Wildcard character in config json

Many thanks for this powerful tool! It runs really fast!
But as titled, it would be helpful if wildcard characters can be used in json configure.
Thanks!

relative imports not handled

relative imports within a package get flagged as import could not be resolved
from .test1 import a

to reproduce
you need:
a package directory containing 2 python files:
test2.py

a=1

test1.py

from .test2 import a

-> gets flagged as import could not be resolved by pyright

pyright 1.08 as extension of vscode

python 3.7 from anaconda distribution on windows 10
i have added the files to reproduce the issue

test.zip

Argument of type 'str' cannot be assigned to parameter of type 'Optional[AnyStr]'pyright

I appologize in advance if this is a duplicate. In pyright 1.0.5, executed through VSCode, I believe the following is a bug:

code:

import tempfile
def myfunction(argument: str):
    tempdir = tempfile.mkdtemp(prefix=f"arg_{argument}")

pyright shows the following message, which looks erroneous. mypy does not show an error.

Argument of type 'str' cannot be assigned to parameter of type 'Optional[AnyStr]'

Unable to open <filepath>: File is a directory

Describe the bug
Under windows 10 with the VSCode Extension, the links pyright puts under Problems don't work and show the titular error. The error message does show the full path however.

If I right-click and select copy on one of the problems and paste the json into a text-editor, I can see that the resource field points to /. Under linux the extension works and resource contains the full and correct path.

{
	"resource": "/",
	"owner": "_generated_diagnostic_collection_name_#0",
	"severity": 8,
	"message": "Import 'matplotlib.pyplot' could not be resolved",
	"source": "pyright",
	"startLineNumber": 414,
	"startColumn": 16,
	"endLineNumber": 414,
	"endColumn": 33
}

To Reproduce
Open a python file with issues and click on one of the problems to be redirected to the location.

Expected behavior
Redirect to the problem location.

VS Code extension or command-line
VSCode 1.33 with Pyright v1.0.9

Additional context
Windows 10 Pro 1803
Python 3.7.1 from Anaconda3

Better docs for Type Stubs, how they work, default behavior, etc

I'm using pyright from command line. By default, pyright does not recognize any built-ins. I might be configuring it wrong but the docs don't explain. README mentions Typeshed and the configuration docs say "Pyright ships with an internal copy of some typeshed type stubs". Makes me believe that built-ins should work without extra configuration.

Are they enabled by default? I get errors like:

'len' is not defined (27, 8)
'dir' is not defined (58, 23)
'getattr' is not defined (59, 13)

my config is:

{
    "include": ["/Users/xxx/projects/xxx/django"],
    "venvPath": "/Users/xxx/.envs/",
    "venv": "xxx",
    "pythonVersion": "2.7"
}

Expression of type 'dict' cannot be assigned to return type 'Dict'

When using python's type hinting to designate a function as returning a Dict, and returning an actual dict, pyright flags this as invalid, when I believe it is valid (unless I've been doing type hinting wrong, which is always possible).

Minimal reproduction example

from typing import Dict

def return_a_dict() -> Dict:
    return {}

Inconsistent virtualenv import messages

Describe the bug

This may related to #30

Python packages installed in a virtualenv are showing as import errors ("Import 'foo' could not be resolved"), and yet intellisense and tooltips are displaying correctly. This results in 1000s of errors in the project.

To Reproduce

Prerequisites: both python.venvPath and venv settings have been set.

  1. Install pyenv and pipenv
  2. Install Django into the virtualenv using pipenv install django.
  3. Open a module in a project that imports Django modules
  4. Check the import statements for errors, and
  5. Check specific modules / functions imported from those packages

Expected behavior

Packages installed within the virtualenv should not display an error (red squiggly underline), and Pyright should recognise them.

Actual behavior

The top-level packages are not recognised, but functions imported from those packages are (or appear to be).

Screenshots or Code

Django is installed in the local virtualenv, but django.utils.encoding cannot be resolved.

Screenshot 2019-03-31 at 15 33 44

However, smart_text, a function within the package can be resolved - as it displays tooltips:

Screenshot 2019-03-31 at 15 33 51

And intellisense is working on the packages:

Screenshot 2019-03-31 at 15 53 35

Screenshot showing that VS Code is using the correct virtualenv environment:

Screenshot 2019-03-31 at 15 45 25

VS Code extension or command-line
Running the VS Code extension

pyright command line requiring `venv setting`

When running `pyright -p pyrightconfig.json -v I get the message "venvPath must be used in conjunction with venv setting, which was omitted".

What is exactly meant by 'venv setting'?

Next it is not clear to me what exactly the difference is between the -P option and the -v. Using neither of both options and with my virtual environment however activated, pyright was neither able to find my python installation, saying "No venvPath specified. Falling back on PYTHONPATH: No valid paths found in PYTHONPATH environment variable."

Typehints with classes specified with strings do not work

Example code:

from typing import Optional

def f() -> Optional["K"]:
    return K()

class K:
    def __init__(self):
        self.x = 1

Pyright tells me (under K()):

Expression of type 'K' cannot be assigned to return type 'Optional[str]'

This kind of type hint works with mypy. Is there a workaround?

Type Stub PEP

Together with @rchen152, @Solumin, and @JelleZijlstra I am currently writing a PEP about type stubs. (Progress is currently stalled a bit, since other projects took precedence, but I plan to continue working on it soon.) The PEP includes a reference section with links to existing type checkers and I'd like to include pyright. Could you give a brief, one-line explanation to be included in the PEP about what makes pyright special, compared to the other type checkers?

For reference, here are the existing explanations:

  • mypy -- Optional Static Typing for Python
  • PyCharm -- The Python IDE for Professional Developers
  • Pyre -- A performant type-checker for Python 3
  • pytype -- A static analyzer for Python code

Edit: https://github.com/srittau/type-stub-pep

Any hope for Sublime Text support?

I'd love to see pyright support in other editors. How difficult would it be to port over?

Is it feasible / worth trying to do? Is Microsoft interested in helping that process or should we start a separate repo to build bindings for other editors.

Feel free to close this issue if it's not going to happen.

Not able to locate member from parent class, apparently

Hi, just created a pyrightconfig.json and started experimenting more with pyright against the project I am currently working on. It did find a couple of real bugs already 🐛 thanks! But there are some that appear to be false positives.

One is this one where it complains about a missing member, which is defined in a parent class.

/home/kinow/Development/python/workspace/cylc/lib/cylc/loggingutil.py
  '_open' is not a known member of 'TimestampRotatingFileHandler' (141, 28)

However, the class TimestampRotatingFileHandler extends logging.FileHandler, which declares _open:

    def _open(self):
        """
        Open the current base file with the (original) mode and encoding.
        Return the resulting stream.
        """
        return open(self.baseFilename, self.mode, encoding=self.encoding)

Cheers
Bruno

Unexpected binary operator with matrix multiply (@)

Describe the bug
An incorrect "Unexpected binary operator" error message.

To Reproduce

$ cat hello.py 
import numpy as np
A = np.zeros(10,10)
B = np.zeros(10)

(A @ B).dot(A @ B)

Load in VSCode, and view the results of pyright analysis (v 1.0.7). The first (A @ B) expression is highlighted in red, and shows the "Unexpected binary operator" error message. No error messages are displayed for the second (A @ B).

Expected behavior
No error messages.

image

tuple "index

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior.

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots or Code
If applicable, add screenshots or the text of the code (surrounded by triple back ticks) to help explain your problem.

def foo(self) -> str:
    return 3

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.

tuple "index" is not a known memeber

Describe the bug

a=('1','2')
a.index('1')

A red underscore is shown under "index" method

To Reproduce
type

a=('1','2')
a.index('1')

Expected behavior
no red underscore

Screenshots or Code

a=('1','2')
a.index('1')

VS Code extension or command-line
VS Code extension v1.0.8

Additional context

Usage of dir on a Module throws an error

Describe the bug
When running the builtin dir function on an imported module an error is shown:
Argument of type 'Module' cannot be assigned to parameter of type 'object'

To Reproduce

import builtins

dir(builtins)

Expected behavior
No error is thrown for this valid usage of dir.

VS Code extension or command-line
VS Code

Additional context
Python 3.6 (Anaconda)

Automatically add type annotations

It would be nice if pyright could add type annotations to existing code bases when it can properly deduce the variable/argument types.

`if isinstance(instance, SuperClass):` loses type

Sort-of the reverse of #24: InstanceOfTypeConstraint constrains the subject's type to None/Never when it's checked against a superclass.

Maybe this should be a no-op instead? I'm not entirely sure, but mypy doesn't flag this as an error.

class SuperClass:
    def __init__(self) -> None:
        self.property: None = None

class MyClass(SuperClass):
    pass

def f(instance: MyClass) -> None:
    if isinstance(instance, SuperClass):
        print(instance.property)
$ npx [email protected] server/src/tests/samples/isinstance.py
Finding source files
Found 1 source files
Analyzed 1 file in 0.981sec
/mnt/c/Users/_/pyright/server/src/tests/samples/isinstance.py
  'property' is not a known member of 'None' (10, 24)
1 error, 0 warnings

Equivalent example with object instead of an explicit superclass:

class MyClass:
    def __init__(self) -> None:
        self.property: None = None

def f(instance: MyClass) -> None:
    if isinstance(instance, object):
        print(instance.property)

Can't recognize venv settings

My project is based on django, with virtualenv.

{
  "typingsPath": "./typestubs",

  "reportTypeshedErrors": false,
  "reportMissingImports": true,
  "reportMissingTypeStubs": false,

  "executionEnvironments": [
    {
      "root": "./",
      "venv": "./.venv",
      "extraPaths": [
        "./3rd-modules"
      ]
    }
  ]
}

.venv is the vritualenv environment directory, but I still get django.xx could not be resolved errors. I have tried set venvPath to "./" but still not work.

  Import 'django.db' could not be resolved

Exited with code 2

Describe the bug
Use pyright in tox test env, the result has no errors but exited with code 2.

py36-pyright run-test: commands[0] | npx pyright -p .
Loading configuration file at /xxx/pyrightconfig.json
Finding source files
Found 8 source files
0 errors, 0 warnings 
Find Source Files:    0.002sec
Read Source Files:    0.001sec
Tokenize:             0.106sec
Parse:                0.264sec
Post-parse Walker:    0.215sec
Semantic Analyzer:    0.349sec
Type Analyzer:        1.339sec
ERROR: InvocationError for command /home/harold/.nvm/versions/node/v11.10.0/bin/npx pyright -p . (exited with code 2)

______________ summary ______________
ERROR:   py36-pyright: commands failed

To Reproduce
config json

{
  "include": [
    "context",
    "tests"
  ],
  "ignore": [
    ".tox",
    ".pytest_cache"
  ],

  "typingsPath": "typestubs",
  "venv": "/xxx/virtualenvs/xxx-4EtOuWbY",

  "reportTypeshedErrors": true,
  "reportMissingImports": true,
  "reportMissingTypeStubs": false,

  "pythonVersion": "3.6",
  "pythonPlatform": "Linux",

  "executionEnvironments": [
    {
      "root": "testContext"
    }
  ]
}

Expected behavior
It indicates the reason if invocation with exit code 2 or not throw this error...

command-line
version: 1.0.8

Importing decimal library causes error

Describe the bug
When importing the python standard decimal library, an error is given: An internal error occurred while performing type analysis

To Reproduce
Have a file where import decimal is present.

Expected behavior
No error for standard libraries

Screenshots or Code

import decimal

VS Code extension or command-line
VSCode extension

Additional context
Python version: 3.6.5 (Anaconda)

Import 'yaml' could not be resolved

Describe the bug
Hi, I'm new to pyright (in vscode) ... it's perhaps a dumb question, but I don't reach to resolve myself ;-)

Why this script works like a charm
Capture du 2019-04-04 18-14-11
and why the import statement is red-underlined (Import 'yaml' could not be resolved) ?

To Reproduce
pip install pyyaml, run vscode, type the script

Expected behavior
the import statement should be ok

Additional context
I don't use any venv thing. It's only pure installed python3, under ubuntu latest LTS

Support for PYTHONPATH

Hi,

I just tried the command line (thanks for publishing it to npm registry!), and it seems to be working! Except for some missing imports, but I assume pyright probably is not processing the PYTHONPATH yet?

Here's an example:

~/Development/python/workspace/cylc/lib/cylc$ PYTHONPATH=$(pwd -P)/../ pyright -P . batch_sys_manager.py
Finding source files
Found 1 source files
Analyzed 1 file in 1.7sec
/home/kinow/Development/python/workspace/cylc/lib/cylc/batch_sys_manager.py
  Import 'cylc.task_message' could not be resolved (119, 6)
  Import 'cylc.cylc_subproc' could not be resolved (122, 6)
  Import 'cylc.task_job_logs' could not be resolved (123, 6)
  Import 'cylc.task_outputs' could not be resolved (125, 6)
  Import 'cylc.wallclock' could not be resolved (126, 6)
  Import 'parsec.OrderedDict' could not be resolved (127, 6)
  'batch_sys' may be unbound (399, 24)
  'batch_sys' may be unbound (411, 24)
  'batch_sys' may be unbound (417, 25)
  'rec_id' may be unbound (474, 12)
  'text' may be unbound (475, 29)
  'rec_id' may be unbound (476, 25)
  'os.getpgid' has type 'Unbound' and is not callable (404, 39)
  'os.killpg' has type 'Unbound' and is not callable (404, 29)
  'KILL_CMD_TMPL' is not a known member of 'Unbound' (417, 35)
  'match' is not a known member of 'Unbound' (476, 32)
  'close' is not a known member of 'None' (753, 28)
11 errors, 6 warnings 
Find Source Files:    0.001sec
Read Source Files:    0.001sec
Tokenize:             0.075sec
Parse:                0.187sec
Post-parse Walker:    0.141sec
Semantic Analyzer:    0.25sec
Type Analyzer:        1.001sec

But if instead of pyright I execute python, the import statements that failed, this time will work.

~/Development/python/workspace/cylc/lib/cylc$ PYTHONPATH=$(pwd -P)/../ python
Python 3.7.2 (default, Dec 29 2018, 06:19:36) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cylc.task_message
>>>

Please come to the Typing Summit

If you can, please join us at the Typing Summit at the upcoming PyCon. Here's a copy of the invitation:

The typing summit is primarily a place for developers of type checkers to collaborate, but we are also inviting (potential) users of type checkers. For example, there are plans to extend the standard Python type system with features intended to support numpy, Pandas, tensorflow and similar libraries, and we will discuss these at the summit. Therefore developers and power-users of such frameworks are especially welcome at the summit.

With Ewa's and Dropbox's help I've arranged a room at PyCon.

When: Thursday May 2nd, 1-5 pm (i.e. the day between the Language Summit and the conference proper)
Where: Room 6 at PyCon in Cleveland

If you're planning to attend, please fill out this form:

https://goo.gl/forms/rG9dVTBbgyBgDK8H2

Also please join the [email protected] mailing list!

Hope to see you there,

--Guido

How to get pyright to find third-party libraries?

I'm try to use the VSCode plugin and in my code where I have import requests it's giving the error: Import 'requests' could not be resolved.

I've created a file pyrightconfig.json with the following:

{
  "typeshedPath": "~/git/typeshed",
  "pythonPath": "/usr/bin/python3"
}

I've also tried setting pythonPath to:

  • /usr/lib/python3.7/site-packages/
  • /usr/lib/python3.7/

None of those have seemed to have any impact on it finding the "requests" module.

Generators can be exited by a naked return

Hi, given this code

from typing import Iterable

def foo(n: int) -> Iterable[int]:
    for j in range(n):
        if j > 13:
            return

        yield j

I'm getting

  Expression of type 'None' cannot be assigned to return type 'Iterable[int]' (7, 13)
  Function with declared type of Iterable[int] must return value (4, 20)

But as per PEP-479, I can exit a generator using a return, without specifying any return values. So, unless I misunderstood something - when in a generator, returns should be handled differently.

(mypy does not trigger anything)

Add documentation for running from the command line

Hi,

I do very little JS & TS (have two projects with Vue.js, still with ES6, to be migrated). The node dependency is not an issue for me to use pyright, and coming from a Java background I do miss more tools like SpotBugs, PMD, CheckStyle, clirr, etc.

However, I am still somewhat more confident when using PyCharm rather than VS Code - though for editing small files I prefer VS Code. The README file mentions the command line, and I tried finding a task in the package.json files that would allow me to produce a binary to be called from the command line in Ubuntu, without luck.

I hate opening issues in GitHub projects for questions/support like this one, sorry. But I really would like to play more with pyright in an environment I am more faimliar, can debug, use other linters/analyzers, and see how it goes. Promise to report all issues and try to contribute back.

Cheers
Bruno

VS Code: modules incorrectly highlighted as unresolved

Describe the bug
Imported modules that are not part of the the Python standard library, are incorrectly highlighted as missing imports in VS Code (Python 3.6, Conda) when using PYRIGHT even though they are successfully imported.

Expected behaviour
Successful imports should not be highlighted as missing imports.

Screenshots
image

System Information Tested

  • OS: Windows 10
  • VS Code 1.32.3
  • Python 3.7 (Conda)

Additional context
This issue may be related to #8 but different in that modules are successfully imported.

site-packages path issue

Describe the bug
Seems like the site-packages path can be different.
According to Python 3 venv spec:

It also creates an (initially empty) lib/pythonX.Y/site-packages subdirectory 
(on Windows, this is Lib\site-packages).

Also virtualenv spec says:

Packages installed in this environment will live under ENV/lib/pythonX.X/site-packages/.

My reading of this part of the code is that only one path is used.
Could you please recheck it?

To Reproduce
macOS 10.14
python 3.7
pyright 1.0.8

Create a virtual env with:
python3 -m venv ~/.venv/dev

site-packages path:
~/.venv/dev/lib/python3.7/site-packages

Expected behavior
pyright checks the ~/.venv/dev/lib/python3.7/site-packages patch.

Import resolution fails for pattern "from . import X"

Describe the bug
Python allows the pattern "from . import X" which is equivalent to "import X" (or "from . import X as Y", which has no equivalent). Pyright currently doesn't handle this case correctly. It treats all such symbols as undefined and doesn't report any error.

VS Code extension or command-line
Pyright 1.0.8

PYRIGHT performance

This may be just me -- or not an issue per se -- but I have not noticed a (substantial) improvement in speed when compared to other Python static typing tools (e.g mypy) -- at least when used in small to medium size projects. In VS Code (Windows 10), loading modules' metadata can take several seconds. Is this a known 'issue' or is this type of behaviour expected?

Dataclass constructors are handled incorrectly

Python Dataclasses (introduced in PEP 557 and introduced in 3.7) automatically generate __init__ methods based on the class's attributes. Here's a simple example that works:

from dataclasses import dataclass

@dataclass
class Bar():
    foo: int

bar = Bar(foo=5)
bar2 = Bar(5)

Pyright, however, doesn't understand this. Here's the output of npx pyright -p {config_file}:

  No parameter named 'foo' (9, 11)
  Expected 0 positional arguments (10, 12)

FWIW, none of the other type checkers seem to understand dataclasses either. (I haven't checked the others recently though.)

`isinstance(instance, SubClass)` loses type instead of narrowing

Given an instance of a SuperClass, I would expect isinstance(instance, SubClass) to narrow the type of instance to SubClass in the following branch. Instead, the type appears to have been lost and replaced with NoneType.

class SuperClass:
    def __init__(self) -> None:
        self.property: bool = True

class SubClass(SuperClass):
    pass

def function(instance: SuperClass) -> None:
    if isinstance(instance, SubClass):
        print(instance.property)
$ mypy --strict example.py && echo "no errors"
no errors
$ pyright example.py
Finding source files
Found 1 source files
Analyzed 1 file in 1.229sec
/Users/jbanks/Desktop/example.py
  'property' is not a known member of 'None' (10, 24)
1 error, 0 warnings

For a slightly smaller example, we get the same error narrowing from the base object type:

class MyClass:
    def __init__(self) -> None:
        self.property: bool = True


def function(instance: object) -> None:
    if isinstance(instance, MyClass):
        print(instance.property)

Unknown alert is displayed when importing an external library.

Describe the bug
When importing a library of foreign nature, even if it is normal, "Import [library_name] could not resoleved" will be warned.

To Reproduce
Import library to your code.
Example

import numpy

Expected behavior
No warning.

Screenshots or Code
image

VS Code extension or command-line
VS Code extension, var1.0.9

Unexpected function return value warning in a while loop

Describe the bug
When a function return in a while True loop, pyright will report 'Function with declared type of (declared return type) must return value'.

To Reproduce
After pyright checked the code, it report this problem.

Expected behavior
Do not report this.

Screenshots or Code

def f(length: int) -> int:
    n = 0
    while True:
        if n >= length:
            return n
        n += random.randint(1, 5) 

VS Code extension or command-line
VS Code extension in 1.0.8

Import could not be resolved for pip packages and local modules

Describe the bug
When opening a file that is known to work in python, all pip based modules and local (to the project) modules are flagged, e.g.: Import 'boto3' could not be resolved

To Reproduce
Import a pip based module or local module. Here is my pyrightconfig.json:

{
    "venvPath": ".",
    "venv": ".venv"
}

Note: my virtual environment is in the project directory as ".venv" (so my python is PROJECT_DIR/.venv/bin/python)

Expected behavior
Valid imports do not get flagged.

VS Code extension or command-line
VSCode extension 1.0.8

To Reproduce
macOS 10.14.2
python 3.6.5 (Anaconda)
pyright 1.0.8

Create a new folder and cd into it via the command line
Create a virtual env with:

virtualenv .venv
. .venv/bin/activate
pip install boto3

Load the following file in VSCode as test.py in the root of the project

import boto3

Additional context
Possibly related to #54, but am not sure.

Unable to initialize a constrained defaultdict

My code has a collections.defaultdict mapping from strs to ints, defaulting to 0 (int()) for missing values. I've been using the following annotation with MyPy to enforce those types.

from collections import defaultdict
from typing import DefaultDict

x: DefaultDict[str, int] = defaultdict(int)
$ mypy --strict example.py && echo "no errors"
no errors

However, Pyright tells me that the assignment is illegal.

$ pyright example.py && echo "no errors"
Finding source files
Found 1 source files
Analyzed 1 file in 1.162sec
/Users/jeremybanks/example.py
  Expression of type 'defaultdict[Any, Any]' cannot be assigned to type 'DefaultDict[str, int]' (4, 4)
1 error, 0 warnings

Few errors in the VSCode console when switching between files

Hi,

Installed VSCode to try out pyright. Then opened the folder of the project I am currently working. Installed the Python extension, and then pyright latest version from git (i.e. installed by choosing the binary created after npm run package).

I noticed now that when I open a file, like lib/cylc/__init__.py for instance, the VS Code console says

/home/kinow/Development/python/workspace/cylc/lib/cylc/__init__.py opened.
file:///home/kinow/Development/python/workspace/cylc/lib/cylc/__init__.py closed.
[Error - 6:37:33 PM] Notification handler 'textDocument/didClose' failed with message: Cannot read property 'isTracked' of undefined

When I open another file such as lib/cylc/network/__init__.py, sometimes it says:

/home/kinow/Development/python/workspace/cylc/lib/cylc/network/__init__.py opened.
file:///home/kinow/Development/python/workspace/cylc/lib/cylc/network/__init__.py closed.

But sometimes after opening other files first, it says:

/home/kinow/Development/python/workspace/cylc/lib/cylc/network/__init__.py opened.
Error performing analysis: {}
file:///home/kinow/Development/python/workspace/cylc/lib/cylc/network/__init__.py closed.
[Error - 6:40:26 PM] Notification handler 'textDocument/didClose' failed with message: Cannot read property 'isTracked' of undefined

I suspect there is some state data being kept between files opened in the editor, and switching between files seems to trigger some case where the previous object is undefined?

Had a look at the code, and was going to try to write a test, but npm run test in the /server/ folder is failing for me.

Thanks for pyright BTW!

Cheers
Bruno

No warnings when the return value type is wrong.

Thanks for publishing the great extension! I'm very glad to check types quickly in VSCode.

But when I tried it, I found an unexpected behavior. Pyright do not warn below code have type missmatch.

def add(a: int, b: int) -> int:
    return float(a + b)

and

def add(a: int, b: int) -> str:
    return a + b

mypy warns same code.

I confirmed this behavior in version 1.0.4.

Leaking code helper processes

I find pyright processes consuming 100% CPU. And even if I exit VS Code the processes are still running

49856   ??  R     32:25.19 /Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper.app/Contents/MacOS/Code Helper /Users/silok/.vscode/extensions/ms-pyright.pyright-1.0.4/server/server.js --node-ipc --clientProcessId=49675

Document how to run Pyright from a git branch

I just tried out Pyright and am encountering internal errors. I would like to run Pyright directly from a git branch, or if that is not possible, then with minimal fiddling, so that I can file bug reports against master (or whatever branch I should be testing).

I have been using mypy for quite a while now, and I've found that the only way I can be productive is if:

  • I can install and run the latest branch of mypy;
  • I can typecheck with my own fork of typeshed (which I can then make PRs from).

I think if the developers took a few minutes to make a short list of setup steps in docs/ then they would see a payoff pretty quickly in terms of bug reports, PRs and relevant fixes to typeshed.

Pyright looks great, and I'd love to start using it! Thanks.

Ignore file/directory support

I would really like a configuration option in the extension to have support for ignoring files/directories like in .gitignore. I presently have a folder of auto-generated python files (via swagger-codegen) that I can't fix (because they'll just get overwritten), so VS Code throws a lot of errors over these files.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.