Static type checker for Python

Overview

Pyright

Static type checker for Python

Speed

Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fast incremental updates when files are modified.

Configurability

Pyright supports configuration files that provide granular control over settings. Different “execution environments” can be associated with subdirectories within a source base. Each environment can specify different module search paths, python language versions, and platform targets.

Type Checking Features

  • PEP 484 type hints including generics
  • PEP 526 syntax for variable annotations
  • PEP 544 structural subtyping
  • PEP 561 distributing and packaging type information
  • PEP 563 postponed evaluation of annotations
  • PEP 585 type hinting generics in standard collections
  • PEP 586 literal types
  • PEP 589 typed dictionaries
  • PEP 591 final qualifier
  • PEP 593 flexible variable annotations
  • PEP 604 complementary syntax for unions
  • PEP 612 parameter specification variables
  • PEP 613 explicit type aliases
  • PEP 647 user-defined type guards
  • Type inference for function return values, instance variables, class variables, and globals
  • Type guards that understand conditional code flow constructs like if/else statements

VS Code Integration

Pyright ships as both a command-line tool and a VS Code extension that provides many powerful features that help improve programming efficiency.

VS Code Language Features

The VS Code extension supports many time-saving language features including:

  • Intelligent type completion of keywords, symbols, and import names appears when editing
  • Import statements are automatically inserted when necessary for type completions
  • Signature completion tips help when filling in arguments for a call
  • Hover over symbols to provide type information and doc strings
  • Find Definitions to quickly go to the location of a symbol’s definition
  • Find References to find all references to a symbol within a code base
  • Rename Symbol to rename all references to a symbol within a code base
  • Find Symbols within the current document or within the entire workspace
  • View call hierarchy information — calls made within a function and places where a function is called
  • Organize Imports command for automatically ordering imports according to PEP8 rules
  • Type stub generation for third-party libraries

Built-in Type Stubs

Pyright includes a recent copy of the stdlib type stubs from Typeshed. It can be configured to use another (perhaps more recent or modified) copy of the Typeshed type stubs. Of course, it also works with custom type stub files that are part of your project.

Command-line Tool or Visual Studio Code Extension

Pyright includes both a command-line tool and an extension for Visual Studio Code that implements the Language Server Protocol.

For rich Python editing and debugging capabilities with Visual Studio Code, be sure to also install the official Microsoft Python extension for Visual Studio Code as Pyright only provides syntax and type checking.

Installation

VS Code Extension

For most VS Code users, we recommend using the Pylance extension rather than Pyright. Pylance incorporates the pyright type checker but features additional capabilities such as IntelliCode and semantic token highlighting. You can install the latest-published version of the Pylance VS Code extension directly from VS Code. Simply open the extensions panel and search for pylance.

Vim

For vim/neovim users, you can install coc-pyright, the Pyright extension for coc.nvim.

Alternatively, ALE will automatically check your code with Pyright, without requiring any additional configuration.

Sublime Text

For sublime text users, you can install the LSP-pyright plugin from package control.

Emacs

For emacs users, you can install lsp-mode that includes lsp-pyright. To activate the pyright extension follow the instructions in the docs.

Command-line

The latest version of the command-line tool can be installed with npm, which is part of node. If you don't have a recent version of node on your system, install that first from nodejs.org.

To install pyright globally: npm install -g pyright

On MacOS or Linux, sudo is required to install globally: sudo npm install -g pyright

Once installed, you can run the tool from the command line as follows: pyright <options>

To update to the latest version: sudo npm update -g pyright

Using Pyright with VS Code Python Extension

Pyright’s type-checking functionality and language features are now incorporated into a VS Code extension called Pylance, the officially supported Python Language Server from Microsoft. Pylance is designed to work with the Python extension for VS Code. In addition to Pyright’s functionality, Pylance adds compatibility with several advanced features including IntelliCode for AI-assisted completions. If you are a VS Code user, we recommend that you uninstall Pyright and instead install Pylance. You will get all the benefits of Pyright and more!

Installing both Pyright and Pylance at the same time is not recommended. If both are installed and enabled, you will see duplicate errors, hover text, and completion suggestions.

Documentation

Limitations

Pyright provides support for Python 3.0 and newer. There is currently no plan to support older versions.

Community

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

FAQ

Q: What is the difference between Pyright and Pylance?

A: Pyright is an open-source Python type checker and language server. Pylance leverages Pyright’s functionality with additional features, some of which are not open-sourced.

Q: What is the long-term plan for Pyright?

A: Pyright is now an officially-supported Microsoft type checker for Python. It will continue to be developed and maintained as an open-source project under its original MIT license terms. The Pyright extension for VSCode is a reference implementation and is not guaranteed to be fully functional or maintained long-term.

Contributing

This project welcomes contributions and suggestions. 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.

Comments
  • reportUnusedVariable ignore pattern

    reportUnusedVariable ignore pattern

    Is your feature request related to a problem? Please describe.

    PyRight at present seems to have no way to fine tune the reportUnusedVariable setting to ignore variables matching certain patterns. When implementing a function/method with a third-party-specified interface, it often happens that there will be some function arguments that you write out but don't use. It should be possible to suppress diagnostics for these "expected" unused arguments without turning off unused variable warnings entirely. But at present, it appears that reportUnusedVariable can only be toggled entirely on or off.

    Describe the solution you'd like

    A common convention for this situation is to prefix the unused arguments with _. Other static analysis tools permit specification of a pattern that matches variable names for which to suppress unused warnings (see varsIgnorePattern for eslint's no-unused-vars) A similar option could be implemented in PyRight.

    enhancement request addressed in next version 
    opened by smackesey 57
  • Priority of package-stubs PYI files over package PYI files

    Priority of package-stubs PYI files over package PYI files

    Describe the bug I'm working on creating the new pandas-stubs repo. The goal is to provide a wheel that will install as the package pandas-stubs. There are PYI files in there that are different than some of the PYI files that are shipped with pandas. If I install my working copy of pandas-stubs into my environment, then if there is a PYI file in the pandas distribution, that is taking precedence over the PYI file in the pandas-stubs package. It should be the other way around, where the PYI files in pandas-stubs take precedence.

    To Reproduce

    1. Pull https://github.com/pandas-dev/pandas-stubs as of commit https://github.com/pandas-dev/pandas-stubs/commit/5f8cdaa78c5a654e7156ab9ee2473e91627a4dcd
    2. Create an environment based on tests/requirements.txt in that repo.
    3. Build the wheel python setup.py build bdist_wheel
    4. Install the wheel pip install dist/pandas_stubs-1.4.2.220604-py3-none-any.whl
    5. Run pyright -p pyrightdistconfig.json

    What happens is that pyright is finding the PYI files in pandas/_libs/tslibs/*.pyi instead of the ones in pandas-stubs/_libs/tslibs/*.pyi, which will eventually be the public PYI files. The ones shipped with pandas are used for internal testing of pandas and should be ignored by users. If you remove the files in pandas/_libs/tslibs/*.pyi, then the tests pass fine.

    Expected behavior Any stub present in pandas-stubs should override a stub present in the installed version of pandas.

    VS Code extension or command-line

    pyright version 1.1.252

    Additional context Things work fine with mypy in terms of it using the stubs in pandas-stubs when they are installed.

    One other note. It would be useful if when using the --dependencies flag, pyright printed which stub it was using. I get output like this in the CI: /opt/hostedtoolcache/Python/3.9.13/x64/lib/python3.9/site-packages/pandas/util/_print_versions.pyi . That PYI file is not in pandas - it is in pandas-stubs. pyright should indicate that it is using the file in pandas-stubs .

    Also, the failure in CI when using pyright is shown here: https://github.com/pandas-dev/pandas-stubs/runs/6743066046?check_suite_focus=true

    When I added to the CI a hack to remove pandas/_libs/tslibs/*.pyi, then the successful run is shown here: https://github.com/pandas-dev/pandas-stubs/runs/6743079731?check_suite_focus=true

    bug addressed in next version 
    opened by Dr-Irv 38
  • pre-commit hook raising an error about missing `./dist/pyright`

    pre-commit hook raising an error about missing `./dist/pyright`

    Describe the bug

    pyright..................................................................Failed
    - hook id: pyright
    - exit code: 1
    
    internal/modules/cjs/loader.js:1033
      throw err;
      ^
    
    Error: Cannot find module './dist/pyright'
    Require stack:
    - /Users/brettcannon/.cache/pre-commit/repopxecb0be/index.js
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1030:15)
        at Function.Module._load (internal/modules/cjs/loader.js:899:27)
        at Module.require (internal/modules/cjs/loader.js:1090:19)
        at require (internal/modules/cjs/helpers.js:75:18)
        at Object.<anonymous> (/Users/brettcannon/.cache/pre-commit/repopxecb0be/index.js:6:1)
        at Module._compile (internal/modules/cjs/loader.js:1201:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1221:10)
        at Module.load (internal/modules/cjs/loader.js:1050:32)
        at Function.Module._load (internal/modules/cjs/loader.js:938:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) {
      code: 'MODULE_NOT_FOUND',
      requireStack: [ '/Users/brettcannon/.cache/pre-commit/repopxecb0be/index.js' ]
    }
    

    To Reproduce Set up pyright in pre-commit:

     - repo: https://github.com/microsoft/pyright
       rev: 1.1.53
       hooks:
       - id: pyright
    
    opened by brettcannon 35
  • Ignore typing annotations

    Ignore typing annotations

    Pyright should ignore lines with # type: ignore as PEP 484: https://www.python.org/dev/peps/pep-0484/#compatibility-with-other-uses-of-function-annotations

    Screenshot 2019-05-03 18 32 26 enhancement request addressed in next version 
    opened by ivanrvpereira 34
  • Handle `python.pythonPath` deprecation in the Microsoft Python extension

    Handle `python.pythonPath` deprecation in the Microsoft Python extension

    Is your feature request related to a problem? Please describe. The python.pythonPath setting is being deprecated in the Microsoft Python extension. Currently Pyright seems (?) to use this setting to select the correct virtual environment. Removing python.pythonPath from my .vscode/settings.json file breaks Pyright's selection of virtual environment.

    Describe the solution you'd like Update the Pyright VS Code extension to handle this change in the Microsoft Python extension.

    bug addressed in next version 
    opened by sambhare 31
  • Enters infinite loop when home folder contains cyclic symlinks

    Enters infinite loop when home folder contains cyclic symlinks

    Describe the bug My home folder contains Proton (from Steam) and Wine. Wine symlinks the dosdevices/z: folder back to /, to provide Windows applications with access to my home filesystem. When Pyright is run and completion is requested, it scans my home folder, eventually reaching the .wine folder, and then infinitely loops trying to read z: (which is /).

    To Reproduce

    1. Have Wine installed and set up (run winecfg at least once)
    2. Start the Pyright language server via your editor
    3. Try to complete

    Expected behavior To not infinitely loop.

    Editor & OS information Editor: GNU Emacs 27.1 LSP Plugin: lsp-mode 20210402.1701 + lsp-pyright OS: Debian GNU/Linux bullseye/testing

    as designed 
    opened by sin-ack 30
  • Stack overflow when analyzing complex function

    Stack overflow when analyzing complex function

    This is a tracking bug. For the original, see https://github.com/microsoft/pylance-release/issues/2427#issuecomment-1057267292.

    Thanks to @excubo-jg, I was able to get my hands on the code and repro the problem. It involves a method that is over 4000 lines long and has many dozens of local variables (all of them unannotated and therefore require inference), and about a thousand code flow statements (if, else, etc.). This is likely beyond our ability to analyze in a reasonable amount of time with reasonable resources (including stack space). I'll need to look for ways to abandon an analysis attempt for a function of this complexity rather than crashing.

    bug addressed in next version 
    opened by erictraut 29
  • Cannot resolve google.cloud imports when types-protobuf are installed

    Cannot resolve google.cloud imports when types-protobuf are installed

    Describe the bug When types-protobuf stub is installed, google.cloud imports cannot be resolved. I don't think it's a stub bug, because mypy seems to handle this right.

    To Reproduce In a fresh venv:

    pip install types-protobuf
    pip install google-cloud-firestore
    cat > test.py
    from google.cloud import firestore
    ^D
    npx pyright --verbose
    
    No configuration file found.
    No pyproject.toml file found.
    stubPath /home/nullie/work/pyright-bug/typings is not a valid directory.
    Assuming Python platform Linux
    Search paths for /home/nullie/work/pyright-bug
      /home/nullie/work/pyright-bug/node_modules/pyright/dist/typeshed-fallback/stdlib
      /home/nullie/work/pyright-bug
      /home/nullie/work/pyright-bug/typings
      /home/nullie/work/pyright-bug/node_modules/pyright/dist/typeshed-fallback/stubs/...
      /usr/lib/python3.8
      /usr/lib/python3.8/lib-dynload
      /home/nullie/work/pyright-bug/venv/lib/python3.8/site-packages
    Searching for source files
    Auto-excluding /home/nullie/work/pyright-bug/venv
    Found 1 source file
    Could not import 'google.cloud' in file '/home/nullie/work/pyright-bug/test.py'
      Looking for typeshed stdlib path
      Attempting to resolve using root path '/home/nullie/work/pyright-bug/node_modules/pyright/dist/typeshed-fallback/stdlib'
      Typeshed path not found
      Looking in stubPath '/home/nullie/work/pyright-bug/typings'
      Attempting to resolve using root path '/home/nullie/work/pyright-bug/typings'
      Attempting to resolve using root path '/home/nullie/work/pyright-bug/typings'
      Looking in root directory of execution environment '/home/nullie/work/pyright-bug'
      Attempting to resolve using root path '/home/nullie/work/pyright-bug'
      Attempting to resolve using root path '/home/nullie/work/pyright-bug'
      Looking in python search path '/usr/lib/python3.8'
      Attempting to resolve using root path '/usr/lib/python3.8'
      Attempting to resolve using root path '/usr/lib/python3.8'
      Looking in python search path '/usr/lib/python3.8/lib-dynload'
      Attempting to resolve using root path '/usr/lib/python3.8/lib-dynload'
      Attempting to resolve using root path '/usr/lib/python3.8/lib-dynload'
      Looking in python search path '/home/nullie/work/pyright-bug/venv/lib/python3.8/site-packages'
      Attempting to resolve using root path '/home/nullie/work/pyright-bug/venv/lib/python3.8/site-packages'
      Resolved import with file '/home/nullie/work/pyright-bug/venv/lib/python3.8/site-packages/google-stubs/__init__.pyi'
      Looking for typeshed path
      Looking for typeshed stubs path
      Attempting to resolve using root path '/home/nullie/work/pyright-bug/node_modules/pyright/dist/typeshed-fallback/stubs/protobuf'
      Resolved import with file '/home/nullie/work/pyright-bug/node_modules/pyright/dist/typeshed-fallback/stubs/protobuf/google/__init__.pyi'
      Typeshed path not found
    /home/nullie/work/pyright-bug/test.py
      /home/nullie/work/pyright-bug/test.py:1:6 - error: Import "google.cloud" could not be resolved (reportMissingImports)
    1 error, 0 warnings, 0 infos
    Completed in 0.619sec
    

    Expected behavior No errors

    Screenshots or Code from google.cloud import firestore

    VS Code extension or command-line Running pyright 1.1.157 with npx

    Additional context Add any other context about the problem here.

    addressed in next version 
    opened by nullie 29
  • Out of memory crash pyright-langserver

    Out of memory crash pyright-langserver

    Describe the bug

    Traceback

    pyright-langserver crashes when heap allocation exceeds 2GB.

    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    "\n<--- Last few GCs --->\n\n[218990:0x60e5f90]   111947 ms: Mark-sweep (reduce) 2016.8 (2082.9) -> 2015.4 (2082.7) MB, 3144.2 / 0.0 ms  (average mu = 0.123, current mu = 0.004) allocation failure scavenge might not succeed\n[218990:0x60e5f90]   115108 ms: Mark-sweep (reduce) 2016.6 (2082.7) -> 2015.7 (2082.9) MB, 3149.6 / 0.0 ms  (average mu = 0.067, current mu = 0.004) allocation failure scavenge might not succeed\n\n\n<--- JS stacktrace --->\n\nFATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 1: 0xb17ec0 node::Abort() [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 2: 0xa341f4 node::FatalError(char const*, char const*) [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 3: 0xcfe71e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 4: 0xcfea97 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 5: 0xee8d35  [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 6: 0xee987c  [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 7: 0xef77b1 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 8: 0xefad0c v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    " 9: 0xec72bb v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    "10: 0x123052b v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]\n"
    [ERROR][2022-03-23 13:16:03] .../vim/lsp/rpc.lua:420    "rpc"   "pyright-langserver"    "stderr"    "11: 0x16147d9  [node]\n"
    

    I think it happens after this commit https://github.com/microsoft/pyright/commit/c56d750d74571cae86587931d85353d4ce28bf19

    It uses process.memoryUsage().rss as an upper limit, which probably should be v8.getHeapStatistics().heap_size_limit I am not sure consulted this SO question

    To Reproduce Big enough project. You can try forcing this issue using export NODE_OPTIONS="--max-old-space-size=1024"

    Expected behavior Crash doesn't occur, cache discarded before critical threshold is reached.

    Additional context I use this language server in neovim, so startup method probably differs from vscode extension.

    bug addressed in next version 
    opened by m-novikov 26
  • Infinite processing with 1.1.167 (never ends)

    Infinite processing with 1.1.167 (never ends)

    I have 4 projects that I'm currently maintaining that I run pyright on their base directories almost everyday to check the typing.

    After updating to the latest version, one of them starts to run and never finishes. Like, never! It keeps running, without giving me any errors or logs, I can see that one CPU's core is being 100% used, but it never finishes. I waited for almost half an hour and it didn't finish... All that I can see in the output is:

    No configuration file found.
    pyproject.toml file found at /home/bellini/dev/veroo/backend.
    Loading pyproject.toml file at /home/bellini/dev/veroo/backend/pyproject.toml
    No include entries specified; assuming /home/bellini/dev/veroo/backend
    Auto-excluding **/node_modules
    Auto-excluding **/__pycache__
    Auto-excluding .git
    stubPath /home/bellini/dev/veroo/backend/typings is not a valid directory.
    Searching for source files
    Auto-excluding /home/bellini/dev/veroo/backend/.venv
    Found 483 source files
    

    I'm also attaching the verbose output (didn't want to paste it here because it is very long), but it doesn't contain any extra information. After that output it just keeps running indefinitely .

    pyright_verbose.txt

    I don't really know how to give a better bug description here. The source code is proprietary and because of that I cannot share it here, and the other 3 projects that I mentioned are very alike (they have the same base infrastructure and have 90% of the same dependencies) and they don't present that same issue. But I'm open to do something locally to try to give you more info if there's a way.

    bug addressed in next version 
    opened by bellini666 26
  • Import Resolution issue

    Import Resolution issue

    Hi there,

    I use the exact same way to create python venv in every projects. In some projects pyright is able to find those site-packages under venv folder, but some projects just doesn't work.

    I did some experiments to see if I can find any pattern that why it works occasionally. Here is the steps I take:

    mkdir tmp
    cd tmp
    echo "import requests" >> test.py
    python -m venv .venv
    source .venv/bin/activate
    pip install requests
    pyright test.py --verbose
    
    No configuration file found.
    No pyproject.toml file found.
    stubPath /Users/lancewenglin/Dev/tmp/typings is not a valid directory.
    Assuming Python platform Darwin
    Search paths for /Users/lancewenglin/Dev/tmp
      /Users/lancewenglin/.npm/_npx/d494279c469adf60/node_modules/pyright/dist/typeshed-fallback/stdlib
      /Users/lancewenglin/Dev/tmp
      /Users/lancewenglin/Dev/tmp/typings
      /Users/lancewenglin/.npm/_npx/d494279c469adf60/node_modules/pyright/dist/typeshed-fallback/stubs/...
      /Users/lancewenglin/.pyenv/versions/3.7.12/lib/python3.7
      /Users/lancewenglin/.pyenv/versions/3.7.12/lib/python3.7/lib-dynload
      /Users/lancewenglin/.pyenv/versions/3.7.12/lib/python3.7/site-packages
    Searching for source files
    Found 1 source file
    pyright 1.1.265
    /Users/lancewenglin/Dev/tmp/test.py
      /Users/lancewenglin/Dev/tmp/test.py:1:8 - warning: Import "requests" could not be resolved from source (reportMissingModuleSource)
    0 errors, 1 warning, 0 informations
    Completed in 0.467sec
    

    From the logs, looks like pyright cannot find the venv packages.

    However, I tried to source the venv from the other projects that has installed requests package as well:

    deactivate
    source ../project_A/.venv/bin/activate
    pyright test.py --verbose
    
    No configuration file found.
    No pyproject.toml file found.
    stubPath /Users/lancewenglin/Dev/tmp/typings is not a valid directory.
    Assuming Python platform Darwin
    Search paths for /Users/lancewenglin/Dev/tmp
      /Users/lancewenglin/.npm/_npx/d494279c469adf60/node_modules/pyright/dist/typeshed-fallback/stdlib
      /Users/lancewenglin/Dev/tmp
      /Users/lancewenglin/Dev/tmp/typings
      /Users/lancewenglin/.npm/_npx/d494279c469adf60/node_modules/pyright/dist/typeshed-fallback/stubs/...
      /Users/lancewenglin/.pyenv/versions/3.7.12/lib/python3.7
      /Users/lancewenglin/.pyenv/versions/3.7.12/lib/python3.7/lib-dynload
      /Users/lancewenglin/Dev/project_A/.venv/lib/python3.7/site-packages
      /Users/lancewenglin/Dev/project_A/src
      /Users/lancewenglin/Dev/project_A/serverless_utils/python_packages/canoo/python_utils/src
    Searching for source files
    Found 1 source file
    pyright 1.1.265
    0 errors, 0 warnings, 0 informations
    Completed in 0.454sec
    

    pyright works perfectly with venv.

    The only pattern I found is that every old venv I created before works fine, and every newly created venv doesn't work. I've been struggling in this for days.

    Any ideas or suggestions are very appreciate!!!

    as designed 
    opened by lancewl 24
  • Wrapping a list in np.array surfaces a type error otherwise unflagged

    Wrapping a list in np.array surfaces a type error otherwise unflagged

    Describe the bug

    As of Pyright 1.1.285, no error is returned on the following line of code:

    np.array(["".join(random.choices(string.ascii_lowercase, k=20)) for i in range(8000)])

    However, as of Pyright 1.1.286, there is an error:

    Argument of type "LiteralString" cannot be assigned to parameter "population" of type "SupportsLenAndGetItem[_T@choices]" in function "choices"
        "str" is incompatible with protocol "SupportsLenAndGetItem[LiteralString]"
          TypeVar "_T_co@SupportsLenAndGetItem" is covariant
            "str" is incompatible with "LiteralString" (reportGeneralTypeIssues)
    

    The real trouble is this: if I move the list comprehension into a variable, and then wrap that in np.array(variable), neither line triggers an error.

    Somehow, only when wrapping this list comprehension in np.array do I receive an error which has to do with random.choices.

    To Reproduce

    First, in a new virtual environment, install numpy.

    In test.py:

    import random
    import string
    
    import numpy as np
    
    np.array(["".join(random.choices(string.ascii_lowercase, k=20)) for i in range(8000)])
    
    arr = ["".join(random.choices(string.ascii_lowercase, k=20)) for i in range(8000)]
    np.array(arr)
    

    As of Pyright 1.1.286, you will receive this report:

    ~/test/test.py
      ~/test/test.py:6:34 - error: Argument of type "LiteralString" cannot be assigned to parameter "population" of type "SupportsLenAndGetItem[_T@choices]" in function "choices"
        "str" is incompatible with protocol "SupportsLenAndGetItem[LiteralString]"
          TypeVar "_T_co@SupportsLenAndGetItem" is covariant
            "str" is incompatible with "LiteralString" (reportGeneralTypeIssues)
    1 error, 0 warnings, 0 informations
    Completed in 0.945sec
    

    Expected behavior

    Either random.choices cannot accept a LiteralString, in which case it should throw an error regardless of whether it is wrapped in np.array, or it can accept a LiteralString, and it should not. The reporting of an error should not depend on whether that expression is wrapped in np.array.

    bug addressed in next version 
    opened by ntaylorwss 2
  • `isinstance(foo, NoneType)` does not narrow `foo` as `None`

    `isinstance(foo, NoneType)` does not narrow `foo` as `None`

    Describe the bug With a variable foo typed as T | None, the statement isinstance(foo, NoneType) does not narrow foo to be None.

    To Reproduce

    # tmp.py
    from random import getrandbits
    from types import NoneType
    from typing_extensions import assert_never
    
    random_bool = bool(getrandbits(1))
    
    foo: int | None = 123 if random_bool else None
    
    if isinstance(foo, int):
        ...
    elif isinstance(foo, NoneType):
        ...
    else:
        assert_never(foo)
    
    $ pyright tmp.py
    ...
      .../tmp.py:15:18 - error: Argument of type "None" cannot be assigned to parameter "__arg" of type "Never" in function "assert_never"
        Type "None" cannot be assigned to type "Never" (reportGeneralTypeIssues)
    

    Expected behavior I would not expect pyright to give an error; I'd expect pyright to narrow foo as None in the second arm of the if-elif block above.

    Additional context I understand that the annotation foo: int | NoneType might be more technically correct than foo: int | None. However, using the former annotation violates convention and causes pyright to spit out a different error (namely tmp.py:8:23 - error: Expression of type "Literal[123] | None" cannot be assigned to declared type "int | NoneType").

    I discovered this bug when trying to use a match statement as so:

    match foo:
        case int():
            ...
        case NoneType():
            ...
        case _:
            assert_never(foo)  # pyright err: Argument of type "None" cannot be assigned...
    
    enhancement request addressed in next version 
    opened by Jasha10 2
  • Support Union narrowing with Ellipsis

    Support Union narrowing with Ellipsis

    Effectively the same as this issue from mypy

    Ellipsis is a constant in Python, so we're able to do identity checks on it for narrowing.

    This allows supporting using Ellipsis as a sentinel value where None is an accepted input.

    basic example:

    import types
    
    # crude, but valid in more complex cases, such as a fallback when accessing a store
    def get_val(default=...) -> int | types.EllipsisType:
        return default
    
    x = get_val()
    
    if x is not ...:
        reveal_type(x)
    

    reveal_type output:

    Pylance: Type of "x" is "int | ellipsis"
    mypy(note): Revealed type is "builtins.int"
    
    enhancement request addressed in next version 
    opened by antdking 3
  • `__required_keys__` and `__optional_keys__` are not inherited from `TypedDict`

    `__required_keys__` and `__optional_keys__` are not inherited from `TypedDict`

    from typing import TypedDict
    
    class Foo(TypedDict): ...
    
    reveal_type(Foo.__required_keys__)
    reveal_type(Foo.__optional_keys__)
    

    Mypy correctly reports:

    foo.py:5: note: Revealed type is "builtins.frozenset[builtins.str]"
    foo.py:6: note: Revealed type is "builtins.frozenset[builtins.str]"
    

    whereas pyright 1.1.287 reports:

    /tmp/foo.py
      /tmp/foo.py:5:17 - error: Cannot access member "__required_keys__" for type "Type[Foo]"
        Member "__required_keys__" is unknown (reportGeneralTypeIssues)
      /tmp/foo.py:5:13 - information: Type of "Foo.__required_keys__" is "Unknown"
      /tmp/foo.py:6:17 - error: Cannot access member "__optional_keys__" for type "Type[Foo]"
        Member "__optional_keys__" is unknown (reportGeneralTypeIssues)
      /tmp/foo.py:6:13 - information: Type of "Foo.__optional_keys__" is "Unknown"
    2 errors, 0 warnings, 2 informations 
    

    The relevant typeshed code is:

    https://github.com/microsoft/pyright/blob/440d54d68dba4505d1ba85e44abca27f8c5f5486/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi#L792-L797

    (And my Python version is 3.9.2 so this check should evaluate to true ... I ran pyright with --pythonversion 3.9 to make sure but that didn't change anything).

    bug addressed in next version 
    opened by not-my-profile 1
  • [WIP] add a new 'compactSignatureDisplay' option for hover and completions.…

    [WIP] add a new 'compactSignatureDisplay' option for hover and completions.…

    … Currently its defaulted to false so that we insert newline between function parameters, but in tests we enable compact mode so that we don't need to re-write every test when we want to change the display format.

    This time i dont modify printType and restrict the formatting to a higher level in hoverProvider and completionProvider.

    todo:

    • [x] add some actual tests around the new non-compact hover/completion layouts
    • [ ] HeeJae also suggested we re-rewrite printType to use a DisplayStruct under the hood, with a list of string and token kind, so that we can do proper formatting outside of printType. similar to getFuncitonParts but something like getTypeParts

    One important note. this doesn't currently handle the case of a function or overloaded function being assigned to a variable, and then having the variables hover show nicely formatted overloads with parameters separated on an individual line. Variables use 'printType()' and not getFunctionParts() so I dont have access to the separate parts. I probably could get the variables alias type and see if its a function/overload. Will investigate

    example class constructors image

    functions image

    currently if there is only 1 parameter will wont separate out the parens to new lines. Also note I considered 2 options for the closing parens and decided to place the closing paren on a new line, in order to give return type annotations more horizontal space. image

    opened by bschnurr 1
  • Some types cannot be assigned to TypeAlias when TypeAlias is imported from anywhere other than typing

    Some types cannot be assigned to TypeAlias when TypeAlias is imported from anywhere other than typing

    Describe the bug When TypeAlias is imported from anywhere other than typing, Tuple cannot be assigned to a TypeAlias.

    To Reproduce

    1. Create a module that exports TypeAlias
    2. Import TypeAlias from the module created in the previous step
    3. Create an explicit type alias of Tuple

    Expected behavior No error where an alias of Tuple is created

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

    from typing import TypeAlias
    
    __all__ = ['TypeAlias']
    

    Repro.py

    from typing import Tuple
    
    from Compat import TypeAlias
    
    Alias: TypeAlias = Tuple
    
    error: Expression of type "Type[Tuple[_T_co@tuple]]" cannot be assigned to declared type "TypeAlias"
       "Type[type]" is incompatible with "Type[TypeAlias]" (reportGeneralTypeIssues)
    

    VS Code extension or command-line Pylance extension v2022.11.20 Command-line v1.1.279

    Additional context This is a simplified reproduction of an issue I am facing upgrading from Psycopg 3.0.15 to 3.1.4. In 3.1, some implicit type aliases were made explicit.

    needs decision 
    opened by rpmrmartin 7
Releases(1.1.287)
  • 1.1.287(Jan 4, 2023)

    Bug Fix: Fixed false positive error in parser when an assignment expression (walrus operator) is used in a subscript list without parentheses. This was a syntax error in Python 3.8 and 3.9 but is allowed in 3.10 and newer.

    Bug Fix: Fixed regression that caused an incorrect type evaluation in the presence of a doubly-nested loop.

    Bug Fix: Fixed bug that sometimes resulted in incorrect type evaluation of tuple expressions used within a loop.

    Bug Fix: Fixed a bug in the import cycle detection logic that led to some false negatives.

    Enhancement: Addressed type evaluation performance issue by eliminating separate "incomplete type cache" and combining it with the primary type cache.

    Enhancement: Improved error reporting for type mismatch involving a return type that is a TypedDict.

    Bug Fix: Fixed a bug that resulted in a false positive error when resolving nested overloaded function calls where the correct overload match depends on bidirectional type inference.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.286(Dec 28, 2022)

    Bug Fix: Reverted a recent update to the TOML parser that resulted in a regression. This reversion means that some TOML 1.0 features will not be handled correctly.

    Bug Fix: Fixed a bug that resulted in incorrect handling of literals in the TypeVar constraint solver. This involved a pretty significant change to the constraint solver logic — one that eliminated some heuristics and special cases.

    Bug Fix: Fixed a bug that caused target expressions within a chained assignment to be evaluated in the wrong order (right to left instead of left to right). This resulted in false positives and negatives in some cases where one target referred to another target. This change also makes it illegal to use a Python 2-style type comment on a line containing a chained assignment statement, reflecting the fact that Python 3-style variable type annotations are not legal here either.

    Enhancement: Improved handling of TypeVarTuple constraint solving. Previously, if a TypeVarTuple appeared more than once, the corresponding tuple types needed to be identical. The constraint solver now supports the same sort of narrowing/widening within the tuple entries to find the best solution.

    Bug Fix: Fixed a bug that led to a false negative during protocol matching if the protocol class refers to itself within an invariant type argument.

    Enhancement: Improved handling of generic functions passed as arguments to generic higher-order functions. Pyright is now able to solve the type variables for both the generic callback and the called function.

    Enhancement: Updated typeshed stubs to the latest version.

    Enhancement: Improved handling of generic functions passed as arguments to generic higher-order functions that use a ParamSpec. Pyright is now able to solve the type variables for both the generic callback and the called function.

    Bug Fix: Fixed a bug in the code flow engine that resulted in incorrect type evaluation in some cases involving double nested loops.

    Bug Fix: Improved the method override consistency checks to detect the case where an override uses an *args parameter that is not type compatible with the overridden method's parameter types. Thanks to @mehdigmira for this contribution.

    Enhancement: Improved handling of TypeVars that appear only within a Callable within a return type annotation for a function. By a strict reading of PEP 484, these should be bound to the function's scope, but practically, they are bound to the Callable. This allows a function to return a generic callable type. When TypeVars are rescoped in this manner, the TypeVar cannot be referenced within the function body because it is no longer in scope in that context.

    Enhancement: Improved error handling for NewType calls

    Enhancement: Completed initial implementation of PEP 696. Added support for default TypeVar types that refer to other TypeVars.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.285(Dec 21, 2022)

    Enhancement: Implemented a new --level command-line option that allows filtering of 'information' and 'warning' diagnostics.

    Enhancement: Updated TOML parser to one that is compliant with the TOML 1.0 spec.

    Enhancement: Added logic to detect uses of PEP 604 | syntax that generate exceptions due to runtime limitations. In particular, if one of the operands is a string (i.e. a forward reference) and the other is also a string or a class that is not explicitly specialized, this will result in an exception.

    Bug Fix: Fixed recent regression in completion provider that resulted in garbled type information for a symbol that is declared as a function (using a def statement) but transformed into a non-function type using a decorator.

    Bug Fix: Fixed a bug that resulted in a false positive error when an index expression with a numeric literal subscript was used in a loop that included a del statement targeting the same index expression.

    Behavior Change: Modified the overload matching algorithm to match the behavior of mypy when the overload match is ambiguous because an argument evaluates to Any or Unknown. In this case, the call expression evaluates to Unknown. Previously, pyright used the first of the matching overloads in this case.

    Bug Fix: Fixed a bug that led to extremely long type analysis times when determining type compatibility between an recursive type alias and a recursive protocol.

    Bug Fix (contribution from @parched): Fixed recent regression that caused reportImportCycles diagnostic reporting to no longer work.

    Bug Fix: Fixed a bug that resulted in a false positive error when a property setter or deleter contained function-scoped type variables.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.284(Dec 14, 2022)

    Bug Fix: Fixed a bug that resulted in an incorrect type evaluation when using a literal integer index into a tuple that includes an unpacked TypeVarTuple element.

    Behavior Change: Removed diagnostic check that detects a non-ellipsis default value in a stub file. This check was based on a now-outdated best practice. We now recommend that stubs include default values for better usability in language servers.

    Bug Fix: Fixed recent regression that caused the hover text for a function symbol to be improperly formatted if its type was evaluated to something other than a function.

    Enhancement: Exposed new configuration setting analyzeUnannotatedFunctions which corresponds to the --skipunannotated command-line option. Added an information diagnostic for skipped functions.

    Bug Fix: Fixed bug that resulted in an incorrect target range when resolving the declaration of an import. There were cases where "Go To Declaration" would take you to a location within the target file that corresponded to the offset of the import statement within the importing file.

    Bug Fix: Fixed bugs that resulted in false positive errors when assigning a type to a Callable and when accessing members from a type[T] or a T that is bound to type.

    Enhancement: Improved bidirectional type inference for list, set and dictionary expressions when the "expected type" is a union that contains multiple potentially-compatible subtypes.

    Bug Fix: Fixed a bug that led to a false positive error when evaluating a recursive type alias definition that uses a generic type that is parameterized using a bound or constrained type variable.

    Bug Fix: Added missing diagnostic rule in diagnostics reported as part of the reportImportCycles check. Thanks for @parched for this fix.

    Bug Fix: Fixed false positive error in multi-inheritance override check in cases where the override symbol was provided by one of the base classes.

    Enhancement: Updated typeshed stubs to the latest version.

    Behavior Change: Added check for disallowed expression forms used with TypeAlias and with PEP 695 type statement.

    Bug Fix (from pylance): Fixed exclude/include to work with '.' prefixed directories.

    Bug Fix: Fixed a bug that led to a false positive when a NoReturn or Never type argument was used for a covariant type parameter.

    Bug Fix: Fixed regression that resulted in inconsistent behavior when useLibraryCodeForTypes is false and a symbol is imported from a non-py.typed library.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.283(Dec 7, 2022)

    Enhancement: Added support for # pyright: ignore and # type: ignore comments that are not at the start of a comment.

    Enhancement: Improved parse recovery for common indent/dedent conditions.

    Bug Fix: Fixed recent regression that resulted in a false positive when a type[T] was assigned to a Callable[..., T].

    Bug Fix: Fixed a regression related to a recent change in typeshed that caused imports from google.cloud namespace packages to fail.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when assigning an unpacked TypeVarTuple to a regular (non-variadic) TypeVar during constraint solving. This should result in a union of the TypeVarTuple types.

    Bug Fix: Fixed a bug that resulted in a false positive diagnostic when importing a symbol from a "py.typed" library that was imported (and re-exported) from a non-"py.typed" library.

    Bug Fix: Changed ParamSpec capture logic to track the expression used for a default argument value.

    Bug Fix: Fixed a recent regression that led to a false negative when evaluating the type of an unannotated variable in a loop.

    Enhancement: Added support for frozen_default for dataclass_transform.

    Bug Fix: Fixed recent regression that caused a false positive reportShadowedStdlibModules for relative imports and imports starting with _.

    Enhancement: Show doc strings on hover over module names within import statements.

    Enhancement: Updated typeshed stubs to the latest version.

    Enhancement: Added small perf optimization for determining type compatibility between two unions, especially in cases where the number of items in the union is large.

    Bug Fix: Added logic to limit recursion when handling type compatibility checks between two different recursive type aliases that have the same definition.

    Bug Fix: Fixed bug that resulted in a false positive when passing an unpacked dict or unpacked iterable argument to the constructor of a class that has no __init__ and therefore uses object.__init__.

    Bug Fix: Fixed bug that led to a false positive error when using an unpacked argument that has a declared type that is a tuple with an unpacked TypeVarTuple.

    Bug Fix: Fixed bug that resulted in a false positive reportPrivateImportUsage diagnostic when importing from a py.typed library under certain circumstances.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.282(Nov 30, 2022)

    Bug Fix: Fixed bug that resulted in false positive error when a recursive type alias involving a union was used in certain circumstances.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation when assigning a tuple with an unpacked TypeVarTuple to a tuple with a normal TypeVar.

    Bug Fix: Fixed a bug that resulted in a false negative (a missing error) when assigning a union that contains a TypeVar to another union with the same TypeVar.

    Bug Fix: Fixed bug that resulted in incorrect type inference for an instance variable that is assigned different types in different places.

    Bug Fix: Fixed bug in tokenizer that resulted in false positive error when a floating point literal started with one or more leading zeros.

    Bug Fix: Added logic to deal with conflicting namespace packages when one has no __init__.py(i) file and the other does.

    Enhancement: Updated typeshed stubs to the latest version.

    Bug Fix: Fixed a bug that results in a false positive error when a dataclass field in a child class overrides a non-init dataclass field in a parent class.

    Enhancement: Added code to report an error if a from __future__ import x statement is not found at the beginning of a file. This results in a syntax error.

    Behavior Change: Changed reportUnnecessaryTypeIgnoreComment to to ignore # type: ignore comments if enableTypeIgnoreComments is set to false.

    Bug Fix: Fixed a bug that led to an incorrect type evaluation when an empty list or dict literal is included in a list expression with an "expected type" (i.e. bidirectional type inference is being attempted).

    Bug Fix (from Pylance): Fixed recent regression that caused false positive errors to appear when using a multi-root workspace.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.281(Nov 23, 2022)

    Enhancement: Improved parse recovery for ternary expressions that are missing an else or a post-else expression.

    Enhancement: Changed the implicit declared type of a module-scoped doc to be str instead of str | None when a docstring is present at the top of the module.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when dealing with a union of an unpacked TypeVarTuple.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation when dealing with a union of an unpacked TypeVarTuple.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when applying a solved unpacked TypeVarTuple in a Union.

    Bug Fix: Fixed a bug that resulted in a false positive during protocol matching for a protocol that includes a property with a getter whose self parameter is annotated with a TypeVar.

    Bug Fix: Fixed a bug that resulted in sporadic type evaluation errors when a quoted (forward-declared) type was used in a statement with an explicit PEP-613 TypeAlias annotation.

    Bug Fix: Fixed bug that resulted in false positive errors when doing protocol matching for a recursive protocol definition. I needed to increase an internal recursion limit to support this.

    Enhancement: Updated typeshed stubs to the latest.

    Bug Fix: Fixed regression that resulted in errant reportMissingImports diagnostics within stub files.

    Enhancement: Improved parse recovery when a suite contains an unexpected indent followed by a dedent that restores the indentation to that of the suite's body.

    Bug Fix: Fixed a bug in the evaluation of the "with" statement that resulted in a false positive error when a class implements a context manager via its metaclass.

    Bug Fix: Fixed a bug that led to a false positive error when validating the variance of type parameters for a protocol class when a covariant type parameter is used in a return type in the form type[T_co].

    Bug Fix: Fixed a bug that resulted in a false positive error when using a cast to a TypeVar.

    Bug Fix: Fixed a bug in the type evaluator that could lead to unsolved TypeVars if used in a Callable parameter.

    Bug Fix: Fixed recent regression that led to false positive reportUnnecessaryCast diagnostics.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.280(Nov 16, 2022)

    Bug Fix: Fixed bug that led to an incorrect type evaluation (and potential false negative) when an iterable iterates over an unpacked TypeVarTuple.

    Bug Fix: Enabled the Never type to be used as an explicit type argument for a contravariant parameter.

    Bug Fix: Fixed a bug in the type printing logic where it omitted a Union when an unpacked TypeVarTuple is used within a Union.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when the type arguments for a tuple included an unpacked TypeVarTuple. In this case, the type argument should be treated as a Union[*Ts] rather than *Ts.

    Bug Fix: Fixed a bug that resulted in a false positive for the reportIncompatibleMethodOverride check when the base method used an unpacked tuple for the *args parameter and the override used specific parameters.

    Bug Fix: Fixed a bug that resulted in a false negative when a non-frozen dataclass subclasses from a frozen dataclass. This generates a runtime error, so it should be flagged by the type checker.

    Bug Fix: Fixed a bug that resulted in a false positive error related to type narrowing in a match statement when matching against an enum with only one value.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.279(Nov 9, 2022)

    Behavior Change: Changed the way pyright handles the case where a dataclass or dataclass-like class handles a synthesized __init__ if one or more base classes are unknown.

    Bug Fix: Fixed bug in type printer logic that resulted in a triple * before an unpacked TypedDict when it was used with a **kwargs parameter and the TypedDict was generic.

    Bug Fix: Fixed a bug that resulted in a false positive when invoking the constructor for a generic class that uses an unpacked TypedDict with an **args parameter.

    Bug Fix: Fixed regression that caused non-JSON output to be emitted when --verifytypes is used in conjunction with --outputjson.

    Behavior Change: Changed the reportUninitializedInstanceVariable so it doesn't run on stub files.

    Enhancement: Added new diagnostic rule reportShadowedImport that emits a diagnostic if a local module shadows a stdlib module.

    Bug Fix: Fixed a bug that resulted in a false positive when a call expression includes an unpacked argument that is a tuple with a known length.

    Bug Fix: Reverted recent change to the reportUnnecessaryComparison check that introduced a regression.

    Bug Fix: Fixed a bug that resulted in a false negative when a *args parameter with an unpacked tuple is followed by additional keyword-only parameters that are not supplied by a caller.

    Bug Fix: Added code to clean up the temp directory that pyright creates when determining whether the file system is case sensitive.

    Bug Fix: Fixed bug that resulted in false positive error when evaluating an unpacked tuple or TypeVarTuple in an *args parameter annotation.

    Bug Fix: Improved argument/parameter matching for unpacked tuple arguments.

    Bug Fix: Fixed a bug in detection of variance inconsistency with base classes in a class definition.

    Enhancement: Added support for detecting unhashable types within set and dict expressions. These result in a TypeError at runtime.

    Bug Fix: Fixed bug that resulted in poor hover text message for keyword arguments passed to a TypedDict constructor.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when a generic class implicitly referenced one of its own magic methods (e.g. __iter__).

    Enhancement: Added support for recursive type references when using the functional "alternative syntax" for TypedDict.

    Behavior Change: Changed the synthesized __dataclass_fields__ variable in dataclass to be a ClassVar so it cannot be overridden by an instance variable.

    Behavior Change: Changed protocol matching logic to enforce that a protocol with a ClassVar requires that any compatible class also declare the corresponding field as a ClassVar. Previously, any class-scoped variable satisfied the protocol in this case. This change brings pyright and mypy into agreement.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation involving a recursive type alias that is defined as the union of other types, one of which introduces the recursion.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.278(Nov 2, 2022)

    Behavior Change: Changed the reportUnusedImport check to not report an error for "from y import x as x" since x is considered to be re-exported in this case. Previously, this case was exempted only for type stubs.

    Enhancement: Expand enums in negative narrowing of x in y.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation when an f-string uses expressions that are unions of literal strings. The result should be LiteralString, not str.

    Enhancement: Improved the reportUnnecessaryComparison diagnostic check to detect (and properly report) cases where a comparison if literals is always true or always false.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation when creating a union from two generic functions that are parameterized by different ParamSpecs but are otherwise identical.

    Behavior Change: Updated the default Python version from 3.10 to 3.11 now that 3.11 has been released in its final form. Pyright assumes the default version if it is not otherwise told which version to use (explicitly as a setting or command-line argument or implicitly via the selected Python environment).

    Enhancement: Enhanced --verifytypes so it honors the --pythonversion and --pythonplatform command-line arguments and falls back to the selected Python environment to get these values if they are unspecified.

    Bug Fix: Fixed a bug in the type evaluator related to TypeVarTuple that caused it to incorrectly report a type incompatibility between *Ts and *tuple[*Ts]. These are the same type, so they should be compatible.

    Bug Fix: Fixed a bug that results in incorrect specialization of a function or method that uses a TypeVarTuple parameter. The internal flags were being lost including the tracking of class methods and static methods.

    Bug Fix: Added support for unpacked tuple arguments passed to an *args parameter declared with a TypeVarTuple.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.277(Oct 26, 2022)

    Enhancement: Added support for falsy type guard expressions when the evaluated type is a NamedTuples with at least one element. These always evaluate to True.

    Bug Fix: Fixed bug that resulted in a false positive "possibly unbound" error when a builtin symbol is overridden in the global scope within a conditional block.

    Enhancement: Improved error message for TypeVar constraints that contain generics. Fixed a bug that prevented an error message when keyword argument was duplicated in a call to TypeVar.

    Enhancement: Added support for infer_variance parameter to TypeVar as specified in draft PEP 695.

    Bug Fix: Improved consistency of assignment-based type narrowing when the type of the assigned value includes an Any or Unknown type argument that is nested more than one level deep and the expected (declared) value contains a type argument that is not Any.

    Enhancement: Updated typeshed stubs to the latest version.

    Bug Fix: Fixed bug that results in a false positive error when a protocol class implements an overloaded method.

    Bug Fix: Added a workaround for a recent change to the typeshed stub dataclasses.pyi relating to the InitVar class. For Python 3.8, the stub indicates that the InitVar class has a metaclass called _InitVarMeta that has a __getitem__ method that returns a value of type InitVar[Any], but this creates a circularity because the evaluation of the expression InitVar[Any] depends on the return type of _InitVarMeta.__getitem__.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.276(Oct 19, 2022)

    Enhancement: Updated typeshed stubs to the latest version. This includes the removal of stubs for freezegun.

    Enhancement: Added support for draft PEP 698 and the @override decorator.

    Enhancement: Enhanced reportSelfClsParameterName so it applies to overload signatures. In the general case, this check is not applied to functions with decorators because decorators can change the semantics of parameters for the decorated function. But @overload is a special case, and its semantics are well known.

    Enhancement: Extended the defineConstant mechanism to work with conditional statements that contain member access expressions that reference a defined member name.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.275(Oct 12, 2022)

    Bug Fix: Fixed a bug that resulted in an incorrect type evaluation when a TypeVar bound to an Enum class is instantiated.

    Bug Fix: Added a global "cache manager" to track heap usage for all type analyzer service instances. This prevents out-of-memory conditions when many roots are used in a multi-root workspace.

    Behavior Change (from Pylance): Don't treat classes decorated with dataclass_transform as dataclasses for purposes of determining which fields should be represented in the synthesized __init__ method. This was an ambiguity in PEP 681, which was recently clarified.

    Bug Fix: Fixed a bug that resulted in a false negative when using illegal annotation expression forms within a TypedDict inlined (call-based) definition.

    Bug Fix: Fixed a bug in the code flow engine that resulted in incorrect type evaluation in certain cases involving nested loops.

    Bug Fix: Fixed a bug that resulted in a false positive error when a call targets an object with a __call__ that is itself an object with a __call__ method.

    Bug Fix: Added a check for a return statement with an explicit return value within an async generator function. This is considered a syntax error by the Python compiler, so it should be flagged at static analysis time.

    Bug Fix: Fixed a bug that resulted in incorrect handling of binary files (e.g. ".so" or ".pyd" files) within a library when creating stub files.

    Behavior Change: Enhanced the heuristics used to infer the type of an unannotated function parameter with a default value. If that value evaluates to an instance of a class with a private name (i.e. it starts with an underscore), pyright will now assume that the value is potentially a singleton sentinel value similar to None and will infer the type to be a union of that type and Unknown.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.274(Oct 5, 2022)

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation for members of a StrEnum subclass under certain circumstances. This was caused by a circular dependency in ReprEnum caused by pyright's validation of __init_subclass__ as part of class type evaluation. This change moves this validation step from the type evaluator to the checker, eliminating the potential for circular dependencies and improving performance.

    Bug Fix: Fixed a bug that resulted in a false positive error indicating that a type definition relies on itself in a circular manner.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation for constructor calls using bidirectional type inference where the expected type includes TypeVars that are not in scope for the constructor call.

    Bug Fix: Fixed a bug that resulted in incorrect type narrowing based on literal field discrimination (<a>.field == <literal>) where the expression <a> is a member access expression.

    Bug Fix: Fixed a bug in the "--verifytypes" CLI option that resulted in incorrect calculation of the type completeness core in cases where a private symbol with an incomplete type was imported and re-exported from a public module.

    Bug Fix: Fixed a bug that resulted in incorrect analysis when a ClassVar annotation was enclosed in quotes (i.e. a forward reference).

    Bug Fix: Fixed a bug that resulted in a false positive error when a contravariant generic class was specialized with a union type argument used with bidirectional type inference.

    Enhancement: Updated typeshed stubs to the latest.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.273(Sep 28, 2022)

    Bug Fix: Fixed recent regression that resulted in a false positive error related to argument-to-parameter matching.

    Enhancement: Added a missing check for class-scoped covariant or contravariant TypeVars that are used in a base class where the base class defines the corresponding type parameter to be invariant. This leads to a typing hole, so it should be considered an error.

    Bug Fix: Fixed a bug that led to the incorrect inferred type for a parameter in an unannotated __init__ method in the case where the method overrides a method in a base class.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.272(Sep 21, 2022)

    Enhancement: Added bidirectional type inference support for comprehension statements that create generators. This addresses https://github.com/microsoft/pyright/issues/3948.

    Bug Fix: Improved handling of circular dependencies in a generic class hierarchy — in particular, where a class is parameterized by a constrained TypeVar where one of the constraints includes the class or its ancestors. This addresses https://github.com/microsoft/pyright/issues/3955.

    Bug Fix: Fixed false positive reportInvalidTypeVarUse diagnostic in an overload implementation. This addresses https://github.com/microsoft/pyright/issues/3958.

    Bug Fix: Fixed confusing error message when a value is written to a class attribute that is not defined on the class but is defined on the metaclass but with an incompatible type. This addresses https://github.com/microsoft/pyright/issues/3960.

    Enhancement: Updated typeshed stubs to the latest version.

    Enhancement: Improved error message readability for generic class type incompatibilities.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when calling a generic class constructor from within that class implementation. This addresses https://github.com/microsoft/pyright/issues/3927.

    Bug Fix: Fixed recent regression. Default includes/excludes should be used when pyproject.toml is present. This addresses #3965.

    Enhancement: Extended support for method override completions that use member access expression forms in a parameter's default value expression. This addresses https://github.com/microsoft/pylance-release/issues/3374.

    Bug Fix: Fixed false positive error when a call expression provides zero arguments for an unpacked tuple of indeterminate length within a Callable. This addresses #3972.

    Bug Fix: Improved error message for positional parameter count mismatch when the signature contains an unpacked tuple with either a definite or indefinite length.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.271(Sep 14, 2022)

    Bug Fix: Fixed a bug in assertNever internal function that resulted in a crash when attempting to stringify a recursive data structure. This shows up occasionally in the crash telemetry.

    Bug Fix: Fixed an infinite recursion bug in the type printer that shows up occasionally in the crash telemetry.

    Bug Fix: Fixed a bug that resulted in infinite recursion when a global statement is used within the global scope of a module.

    Enhancement: Added new check for an attempt to instantiate Dict, Set, List, or Tuple from typing module. This generates a runtime exception.

    Bug Fix: Fixed recent regression that resulted in a false positive error when defining a variable in a class body and using its own field name as a type annotation.

    Bug Fix: Fixed bug that results in incorrect narrowing for sequence patterns in a match statement in the negative (fall-through) case when the subject type is a tuple of known length but with elements of type Any.

    Enhancement: Added support for quoted TypeAlias type annotation.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when narrowing types for class patterns in a match statement when the matched class is a generic subclass of the subject type.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation when an isinstance type guard results in an intersection type and one of the sources of the intersection is a conditional type.

    Bug Fix: Fixed a bug that resulted in a transient false positive error in certain cases where a member access expression was used within a quoted type annotation.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.270(Sep 7, 2022)

    Enhancement: Improved precision of error handling for tuple, list and set expressions.

    Bug Fix: Fixed a bug that resulted in incorrect type narrowing for literal patterns in a match statement when the target expression type includes an instance of a class that derives from the literal's class (e.g. a subclass of str).

    Bug Fix: Fixed a bug that led to the incorrect inferred return type for a super().__new__(cls) call.

    Bug Fix: Added support for TypeVarTuple to capture an unpacked tuple with unbounded length.

    Bug Fix: Fixed a bug that resulted in unpacked arguments to a class definition going unevaluated, which means that any symbols they referenced were not marked accessed.

    Enhancement: Expanded reportUnusedExpression check to detect unused tuple, dictionary, list and set expressions if they don't contain comprehensions.

    Bug Fix: Fixed a bug that resulted in a false positive when passing a generic function to an overloaded function that requires union expansion to resolve.

    Bug Fix: Fixed type evaluation bug that led to a false positive error when assigning a type conditioned on a bound TypeVar to that same TypeVar in an invariant context.

    Bug Fix (contribution by @timsu92): Fixed incorrect description of reportUndefinedVariable.

    Bug Fix: Fixed bug in type evaluator that caused a false negative in some circumstances when constructing an instance of a generic class within that class implementation.

    Bug Fix: Fixed a bug that resulted in a false negative when an annotated variable was assigned an expression that included the variable's name and the variable was undefined prior to the assignment.

    Enhancement: Updated typeshed stubs to the latest version.

    Bug Fix: Fixed a bug in the type checker that led it to conclude that two types were the same even though they were declared in separate modules. This occurred when the types had the same (local) name and both modules were located within project directories that contained characters that are invalid for module paths in an import statement (e.g. "-").

    Enhancement: Updated PEP 695 functionality to reflect the latest changes in the spec.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.269(Aug 31, 2022)

    Bug Fix: Fixed a bug that resulted in the reportImportCycles check to sometimes fail to detect and report some import cycles.

    Bug Fix: Fixed bug that resulted in a false positive error when specifying a metaclass that contains an __init__ method with unannotated parameters.

    Bug Fix: Fixed a bug that led to a false negative when assigning a concrete type to an instance variable with a generic (class-scoped) type.

    Enhancement: Enhanced the type(x) is y type guard logic to support the case where x is typed with a TypeVar bound to a class.

    Bug Fix: Fixed a bug that resulted in a false positive error when determining type compatibility of a generic type with an invariant type parameter and a type argument that is a union which includes an instance of a class and an instance of a subclass.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation when solving for a contravariant type variable when a union of callables is passed as an argument.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.268(Aug 24, 2022)

    Behavior Change: Exempted __new__ from parameter covariance check. This is consistent with __init__, which is already exempted from this check.

    Bug Fix: Fixed a bug that resulted in a false negative when using an unparenthesized assignment expression in an assert statement. Also improved the error messages and parser recovery for incorrect use of a unparenthesized assignment expressions.

    Bug Fix: Fixed a bug that resulted in a false positive when analyzing a call to an instance method that omits a self parameter and instead uses *args.

    Enhancement: Improved error reporting for dict literal expressions that are assigned to TypedDict types. Previously, the entire dict literal was included in the error range. Now the range is limited to a specific dictionary entry if there is only one error.

    Enhancement: Extended type narrowing support for x in y pattern where y is a tuple of known length that includes literal types. In this case, negative ("else") type narrowing can be applied if x is a union that includes literals.

    Behavior Change: Increased the code complexity limit that controls whether pyright performs return type inference for functions that have no parameter type annotations. This can be quite expensive, and without parameter types, the results are often low quality. Beyond a certain point, we just skip the expensive analysis and infer a return type of Unknown. The previous limit was quite low. This increases the limit in an attempt to handle return type inference in more of these cases.

    Enhancement: Added a missing check for a **kwargs parameter immediately after a keyword-only separator * parameter. This generates a compiler error in Python.

    Enhancement: Updated typeshed stubs to the latest version.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.267(Aug 17, 2022)

    Bug Fix: Fixed bug that caused error to be suppressed when calling assert_never with bad arguments (incorrect number, etc).

    Enhancement: Added support for dictionary expansion of a TypedDict within a dictionary literal expression.

    Enhancement: Extended support for union expansion of constrained type variables when performing overload matching.

    Bug Fix: Fixed a bug that resulted in different type evaluation behaviors depending on the order of callable types within a union.

    Bug Fix: Fixed bug that resulted in a false positive error when the second argument to a type constructor call includes a tuple that includes a type class.

    Bug Fix: Fixed a bug that resulted in incorrect type evaluation when a generic type alias consists solely of a type variable or a type variable wrapped in Annotated.

    Bug Fix: Fixed bug in parser that resulted in crash when a soft keyword was used as a class pattern keyword argument name.

    Bug Fix: Fixed a bug in the special-case logic that handles __all__.extend(<submodule>.__all__) so it better handles the case where <module> is imported using an import statement of the form from x import submodule.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.266(Aug 8, 2022)

    Bug Fix: Fixed a bug that caused a false positive error when using a list comprehension within a method that is overloaded to accept either a LiteralString or a str. The incorrect overload was chosen in some cases, picking the LiteralString variant rather than the str variant even though LiteralString variant generated type errors.

    Bug Fix: Fixed a bug that caused incorrect type evaluation because of stale module paths that are cached for specific source files. Module paths are dependent on the list of configured import resolution paths, so when the import resolution paths change, we may need to recompute the module path for a source file.

    Bug Fix: Fixed a bug that resulted in a false negative when a del statement targeted a symbol that was unbound (i.e. referenced before assigned) within a function.

    Behavior Change: Changed behavior of assert_type to treat Any the same as Unknown for purposes of type comparison. There is no way to express an Any type explicitly in the Python type system because it is, by definition, an "implicit" Any.

    Bug Fix: Fixed a bug that resulted in a false negative when evaluating binary operations that involve unions for either the LHS or RHS or both.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation when bidirectional type inference was used along with a type alias that was involved in a circular declaration.

    Bug Fix: Fixed a bug that resulted in a false positive error when LiteralString was used as the base type in an index expression.

    Behavior Change: Changed the --verifytypes command to skip docstring checks for overloads and for property setters and deleters.

    Bug Fix: Fixed a bug that resulted in a false positive when evaluating type compatibility of a type that includes an invariant type argument consisting of a union that contains a generic callable.

    Enhancement: Enhanced support for handling of functions that return NoReturn to include support for overloaded functions where some of the overloads return NoReturn and others do not.

    Enhancement: Updated typeshed stubs to the latest version.

    Enhancement: Added better verbose logging for the case where an import cannot resolve the source file leading to a reportMissingModuleSource diagnostic.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.265(Aug 3, 2022)

    Bug Fix: Fixed two type evaluation bugs that caused false positive errors when using join method with LiteralString and when a format string is interpreted as a LiteralString.

    Bug Fix: Fixed false positive errors that resulted from the previous change to format string type inference.

    Enhancement: Updated typeshed stubs to the latest version.

    Bug Fix: Fixed a bug that led to sporadic false positive errors for expressions that involve a call to super().

    Bug Fix: Fixed a bug that resulted in a false positive error when assigning a property created through the @property decorator to a variable or parameter annotated with the type property.

    Bug Fix: Fixed a bug that resulted in incorrect bidirectional type inference for constructor calls for generic classes when the expected type was Self.

    Bug Fix: Fixed a bug that resulted in a false positive error when using an unpack operator (*) in a quoted type annotation with versions of Python prior to 3.11.

    Performance: Improved performance of code flow engine in cases where two variables have significant strong interdependencies and are modified within a loop.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.264(Jul 27, 2022)

    Bug Fix: Fixed bug in reportUnnecessaryContains check that resulted in a false positive when the container element type is a TypeVar. The same logic error was present (and fixed) in the type narrowing logic for in expressions.

    Bug Fix: Fixed bug in reportUnnecessaryComparison check that results in a false positive error when comparison chaining is used.

    Bug Fix: Fixed bug that resulted in a false positive error when using a TypedDict that has been narrowed via an assignment to a not-required key.

    Bug Fix: Fixed a bug that resulted in incorrect type inference for unannotated parameters with a default argument value in an __init__ method.

    Enhancement: Added support for _generate_next_value_ override for Enum class.

    Bug Fix: Fixed a bug in the type printer code that resulted in an infinite recursion and crash.

    Behavior Change: Changed reportUninitializedInstanceVariable check to exempt protocol classes.

    Bug Fix: Fixed a bug that resulted in infinite recursion and a crash when inferring return types for functions that returned another function that also has an inferred return type, etc. in a cycle.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.263(Jul 23, 2022)

    Bug Fix: Fixed bug that resulted in inconsistent behavior for types inferred from tuple expressions containing literal entries.

    Bug Fix: Fixed recent regression that resulted in incorrect type evaluation when a forward-referenced recursive type alias was used as an iterable type.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation within case statement in some situations.

    Bug Fix: Fixed bug that resulted in sporadic errors when evaluating index expressions within a loop.

    Performance: Simplified some internal types, which results in less memory usage and better performance.

    Performance: ixed a performance issue (combinatoric explosion) related to TypedDict classes that were narrowed based on a series of in type guard tests.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.262(Jul 20, 2022)

    Performance: Added a faster code path for testing the type compatibility of a non-union type to a union type when the union type contains no unsolved TypeVars.

    Performance: Added optimization in overload path that eliminates one extra validation of arguments in the common case.

    Enhancement: Updated typeshed stubs to latest version.

    Performance: Implemented tighter scoping for contextual evaluation. This improves performance of type evaluation in various use cases including semantic tokens.

    Bug Fix: Fixed bug in type narrowing logic for "in" operator. It was not properly handling the case where the reference (LHS) type was a subtype of the container's element type.

    Enhancement: Added support for new reportUnnecessaryContains diagnostic rule to catch potential bugs in in and not in containment checks.

    Bug Fix: Changed the validation logic for type argument lists when found outside of a type annotation. The normal type annotation restrictions (such as no dynamic variable usage) should not apply in this case.

    Bug Fix: Fixed a bug that caused defineConstants configuration setting not to work with the pyright and pylance VS Code extensions.

    Bug Fix: Fixed a bug in the dataclass logic that resulted in incorrect handling of a dataclass field that is annotated both in the class body and (redundantly) in a method within the same class.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.261(Jul 16, 2022)

    Behavior Change: Reduced the max code complexity constant to lower the cyclomatic complexity threshold for code analysis to prevent crashes with certain highly-complex code.

    Bug Fix: Fixed regression that caused an internal assertion (and therefore a crash) when using an expression that includes two index expressions, one with a string literal and one without, like a[n].b.c['x'].

    Enhancement: Added support for overloaded __getitem__ in iterables for for statements.

    Enhancement: Enhanced the reportIncompatibleVariableOverride check to catch cases where a Final variable overrides a non-Final variable.

    Bug Fix: Fixed bug that resulted in sporadic errors during type evaluation based on evaluation order.

    Bug Fix: Fixed bug in constraint solver that led to a false positive error in some situations where the solution to a TypeVar involved the union of two other TypeVars.

    Bug Fix: Fixed a bug that resulted in an incorrect type evaluation when a generic callable class variable was specialized recursively with type variables for the same class.

    Bug Fix: Improved handling of type consistency checks for unions so the results are less dependent on the order of subtypes within the union.

    Enhancement: Enhanced reportUnnecessaryTypeIgnoreComment to ignore lines that are unreachable.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.260(Jul 13, 2022)

    Bug Fix: Fixed regression that caused an internal assertion to fire, leading to a crash when certain forms of nested index expressions are used.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.259(Jul 13, 2022)

    Enhancement: Enhanced the reportIncompatibleMethodOverride check to handle the case where a method is overridden by an overload and one of the overloads matches the base method.

    Performance: Improved analysis performance in cases where variables within a loop have mutual dependencies.

    Performance: Added performance optimization for a special case that can occur in code without type annotations. It affects "pseudo-generic" classes that are parameterized recursively.

    Performance: Improved analysis performance in some cases by caching return types inferred through call-site inference.

    Enhancement: Updated typeshed stubs to the latest version, which eliminates support for Python 3.6.

    Enhancement: Added support for type narrowing of TypedDict instances based on assignments to a not-required key.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.258(Jul 9, 2022)

    Bug Fix: Fixed a bug that resulted in incorrect type narrowing when using an in expression and the LHS operand is of type type. This situation requires some special casing.

    Bug Fix: Fixed a bug in the handling of generic type aliases that are parameterized by ParamSpecs in the case where an explicit type argument is not provided. The type argument should default to ... in this case.

    Bug Fix: Fixed bug in the expression printer. It was not properly handling a minimal slice (:). This affected certain logging output.

    Performance: Added optimization for slice expression evaluation. It can be skipped in cases where the we are speculatively evaluating the type.

    Performance: Implemented optimization for type evaluation for index expressions. In cases where there are multiple subexpressions separated by commas, we can skip the check for the __index__ magic method.

    Bug Fix: Fixed a bug that resulted in incorrect isinstance type narrowing when one or more of the filter classes was decorated with a class decorator.

    Enhancement: Added support for context managers whose __exit__ method is declared to return "Literal[False]". This is now treated the same as if it is declared to return "None".

    Performance: Improved performance of type evaluations in certain cases where a union contains multiple types whose class hierarchy contains one or more unknown types.

    Bug Fix: Fixed recent regression that resulted in attribution of a type var to the wrong scope when it was used in an __init__ method of a class with a class decorator.

    Bug Fix: Fixed bug that results in incorrect type evaluation when a function with a **kwargs parameter is captured by a ParamSpec in certain circumstances.

    Bug Fix: Fixed bug that resulted in incorrect type evaluation for values within a TypedDict that derives from a TypedDict that has been specialized.

    Bug Fix: Fixed a bug that results in a spurious "argument type is unknown" diagnostic when an unannotated variable used within a loop is also used as the subscript for an index expression.

    Bug Fix: Improved handling of incomplete types passed as arguments to magic methods.

    Bug Fix: Fixed a bug that resulted in infinite recursion when using auto variance inference with certain recursive types.

    Enhancement: Added more complete type validation for __getattr__, setattranddelattr` methods.

    Bug Fix: Fixed a bug that resulted in a false positive when resolving a symbol from a multi-part import when a short form of that same multi-part import was also imported.

    Source code(tar.gz)
    Source code(zip)
Owner
Microsoft
Open source projects and samples from Microsoft
Microsoft
A system for Python that generates static type annotations by collecting runtime types

MonkeyType MonkeyType collects runtime types of function arguments and return values, and can automatically generate stub files or even add draft type

Instagram 4.1k Jan 2, 2023
A static type analyzer for Python code

pytype - ? ✔ Pytype checks and infers types for your Python code - without requiring type annotations. Pytype can: Lint plain Python code, flagging c

Google 4k Dec 31, 2022
Collection of library stubs for Python, with static types

typeshed About Typeshed contains external type annotations for the Python standard library and Python builtins, as well as third party packages as con

Python 3.3k Jan 2, 2023
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 14.4k Jan 5, 2023
A static analysis tool for Python

pyanalyze Pyanalyze is a tool for programmatically detecting common mistakes in Python code, such as references to undefined variables and some catego

Quora 212 Jan 7, 2023
TidyPy is a tool that encapsulates a number of other static analysis tools and makes it easy to configure, execute, and review their results.

TidyPy Contents Overview Features Usage Docker Configuration Ignoring Issues Included Tools Included Reporters Included Integrations Extending TidyPy

Jason Simeone 33 Nov 27, 2022
Robocop is a tool that performs static code analysis of Robot Framework code.

Robocop Introduction Documentation Values Requirements Installation Usage Example Robotidy FAQ Watch our talk from RoboCon 2021 about Robocop and Robo

marketsquare 132 Dec 29, 2022
Pymwp is a tool for automatically performing static analysis on programs written in C

pymwp: MWP analysis in Python pymwp is a tool for automatically performing static analysis on programs written in C, inspired by "A Flow Calculus of m

Static Analyses of Program Flows: Types and Certificate for Complexity 2 Dec 2, 2022
CodeAnalysis - Static Code Analysis: a code comprehensive analysis platform

TCA, Tencent Cloud Code Analysis English | 简体中文 What is TCA Tencent Cloud Code A

Tencent 1.3k Jan 7, 2023
A simple stopwatch for measuring code performance with static typing.

A simple stopwatch for measuring code performance. This is a fork from python-stopwatch, which adds static typing and a few other things.

Rafael 2 Feb 18, 2022
Inspects Python source files and provides information about type and location of classes, methods etc

prospector About Prospector is a tool to analyse Python code and output information about errors, potential problems, convention violations and comple

Python Code Quality Authority 1.7k Dec 31, 2022
Performant type-checking for python.

Pyre is a performant type checker for Python compliant with PEP 484. Pyre can analyze codebases with millions of lines of code incrementally – providi

Facebook 6.2k Jan 7, 2023
Unbearably fast O(1) runtime type-checking in pure Python.

Look for the bare necessities, the simple bare necessities. Forget about your worries and your strife. — The Jungle Book.

null 1.4k Dec 29, 2022
Data parsing and validation using Python type hints

pydantic Data validation and settings management using Python type hinting. Fast and extensible, pydantic plays nicely with your linters/IDE/brain. De

Samuel Colvin 12.1k Jan 5, 2023
pycallgraph is a Python module that creates call graphs for Python programs.

Project Abandoned Many apologies. I've stopped maintaining this project due to personal time constraints. Blog post with more information. I'm happy t

gak 1.7k Jan 1, 2023
Turn your Python and Javascript code into DOT flowcharts

Notes from 2017 This is an older project which I am no longer working on. It was built before ES6 existed and before Python 3 had much usage. While it

Scott Rogowski 3k Jan 9, 2023
Find dead Python code

Vulture - Find dead code Vulture finds unused code in Python programs. This is useful for cleaning up and finding errors in large code bases. If you r

Jendrik Seipp 2.4k Jan 3, 2023
Code audit tool for python.

Pylama Code audit tool for Python and JavaScript. Pylama wraps these tools: pycodestyle (formerly pep8) © 2012-2013, Florent Xicluna; pydocstyle (form

Kirill Klenov 966 Dec 29, 2022
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 2.1k Jan 5, 2023