Static type checker for Python

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.

Owner
Microsoft
Open source projects and samples from Microsoft
Microsoft
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.

  • 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

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

  • 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

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

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

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

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

  • 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!!!

  • Whitelist private attributes

    Whitelist private attributes

    Is your feature request related to a problem? Please describe. We override and call _repr_html_ for integration with IPython, and it would be nice to avoid triggering reportPrivateUsage for this.

    e.g.

    @dataclass
    class Parent:
      children: list[Child]
      def _repr_html_(self):
        return "<ul>{}</ul>".format("".join(child._repr_html_() for child in self.children))
    
    class Child:
      def _repr_html_(self):
        return "<li>Child</li>"
    

    Describe the solution you'd like Add allowedPrivateUsage configuration that takes a list of strings.

    Additional context

  • Put back checking for type for module subnames

    Put back checking for type for module subnames

    Addresses https://github.com/microsoft/pylance-release/issues/3636

    This shortcut added in https://github.com/microsoft/pyright/commit/b02711fd941beb5b85bcf1c754cf2d0ffd645927 to improve perf treats module subnames as not resolvable.

    This makes hover over different parts of an import statement inconsistent.

  • ParamSpec masks captured default values with ellipsis

    ParamSpec masks captured default values with ellipsis

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

    Here is a minimally reproducible example:

    from typing import Callable, Concatenate, ParamSpec, TypeVar
    
    
    P = ParamSpec("P")
    R = TypeVar("R", covariant=True)
    
    
    def decorator(f: Callable[P, R]) -> Callable[Concatenate[int, P], R]:
        def new_func(i: int, *args: P.args, **kwargs: P.kwargs) -> R:
            return f(*args, **kwargs)
        return new_func
    
    
    @decorator
    def a(j: int, k: int = 1) -> float:
        ...
    
    a()
    
    Screenshot 2022-12-01 at 4 30 25 PM

    Is there any reason that the default values couldn't be shown?

    Describe the solution you'd like

    I want the actual default values to be shown, like this:

    (function) a: (int, j: int, k: int = 1) -> float
    
  • Indent errors show more errors than expected

    Indent errors show more errors than expected

    Describe the bug This issue fixed some indent errors but there are other cases: https://github.com/microsoft/pylance-release/issues/3656

    To Reproduce

    def a():
        print('a')
            print('b')
    
    def b():
        print('c')
    

    Expected behavior There shouldn't be an error on def b()

    Screenshots or Code image

  • Numpy dtype disjunction doesn't work like type disjunction?

    Numpy dtype disjunction doesn't work like type disjunction?

    from typing import Any
    import numpy as np
    import numpy.typing as npt
    
    NumpyIntegralArray = npt.NDArray[np.integer[Any]]
    NumpyRealArray = npt.NDArray[np.floating[Any]]
    
    # This works!
    # def smooth_data(values: NumpyRealArray) -> None:
    
    # This doesn't!
    def smooth_data(values: NumpyIntegralArray | NumpyRealArray) -> None:
        pass
    
    total_observed = np.zeros(10)
    smooth_data(np.asarray(total_observed))
    
  • Feature Request: support `# pyright: ignore` not at the start of a comment

    Feature Request: support `# pyright: ignore` not at the start of a comment

    Is your feature request related to a problem? Please describe. Some tools (pyright included) expect their special keyword in a comment to be at the start of a comment. This can be problematic if two of those tools need a comment on the same line.

    One such other example (with a high risk of collision), is mypy (for example to validate that a library will pass both checkers). I can't ignore both pyright and mypy if they have an error on the same line and enableTypeIgnoreComments is turned off (to separate mypy issues from pyright issues in the first place) Same line doesn't even necessarily mean same error. But certain formatters (like black), will force everytihing on a line until the set limit.

    Example (neither will work):

    class Task(Future[_T_co], Generic[_T_co]):  # type: ignore[type-var]  # pyright: ignore[reportGeneralTypeIssues]
      # [...]
      pass
     
    # OR
    
    class Task(Future[_T_co], Generic[_T_co]):  # pyright: ignore[reportGeneralTypeIssues]  # type: ignore[type-var]
      # [...]
      pass
    

    Describe the solution you'd like One solution is support # pyright: ignore even if it's not at the start of the comment. For instance, pylint, bandit, flake8, isort all do it to avoid this exact kind of issue:

    from typing import Any, Any  # pyright: ignore[reportDuplicateImport]  # isort:skip
    
    class CaptureMethodMeta(EnumMeta):
        # Allow checking if simple string is enum
        def __contains__(self, other: str):
            try:
                self(other)  # pyright: ignore [reportGeneralTypeIssues] pylint: disable=no-value-for-parameter
            except ValueError:
                return False
            else:
                return True
    
    def openFile(file_path: str):  # pyright: ignore[reportUnknownParameterType, reportMissingParameterType]  # noqa: N802
        os.startfile(file_path)  # pyright: ignore[reportUnknownArgumentType]  # nosec B606
    

    And given discussions in https://github.com/python/mypy/issues/12358 , I don't think mypy is going to be able to support ignores at the end of the line anytime soon.

    Additional context

    Other possible solutions (but already declined) include block-level comments: https://github.com/microsoft/pyright/issues/2607 and a "next-line" ignore.

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

Dec 2, 2022
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

Nov 30, 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

Dec 2, 2022
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

Dec 3, 2022
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

Dec 6, 2022
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

Nov 27, 2022
Robocop is a tool that performs static code analysis of Robot Framework code.
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

Nov 23, 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

Dec 2, 2022
CodeAnalysis - Static Code Analysis: a code comprehensive analysis platform
CodeAnalysis - Static Code Analysis: a code comprehensive analysis platform

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

Dec 5, 2022
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.

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

Nov 26, 2022
Performant type-checking for python.
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

Dec 3, 2022
Unbearably fast O(1) runtime type-checking in pure Python.
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.

Nov 23, 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

Dec 5, 2022
pycallgraph is a Python module that creates call graphs for Python programs.
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

Nov 29, 2022
Turn your Python and Javascript code into DOT flowcharts
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

Nov 28, 2022
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

Nov 30, 2022
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

Nov 30, 2022
The strictest and most opinionated python linter ever!
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

Dec 5, 2022