basedpyright Documentation

repository·main·Indexed 25 days ago

https://github.com/detachhead/basedpyright

A fork of Microsoft's pyright enhanced with additional type checking improvements and features typically found in Pylance. It includes a baseline feature for managing existing errors, a "recommended" typeCheckingMode by default, stricter diagnostics for redeclarations and duplicate imports, and a browser-adapted version via the browser-basedpyright package.

Tokens
32.5K
Snippets
69
Records
202
Agent score
86%

What's inside basedpyright

  1. Overview of basedpyright (browser edition)

    main

    The browser-basedpyright package is a version of basedpyright specifically adapted to run within a web browser environment. It is an adaptation of the microbit-foundation pyright fork.

    Important Recommendation: Unless you have a specific requirement for a browser-based implementation, it is recommended to use the standard basedpyright package installed via PyPI instead.

  2. Overview of basedpyright features

    main

    basedpyright is a type checker that provides several advantages over the standard Pyright:

    • Pylance features in any editor: Re-implements many features exclusive to Microsoft's closed-source Pylance extension, allowing them to be used outside of VS Code.
    • Easy to install & pin: Can be installed directly from PyPI without requiring a NodeJS installation. The VS Code extension uses the same version as the CLI, ensuring consistency between editor diagnostics and CLI checks.
    • Strict by default: Includes new diagnostic rules to detect serious issues that Pyright misses, with all rules enabled by default.
    • Baseline support: Allows for the effortless adoption of stricter type checking rules in existing projects without requiring immediate updates to legacy code.
    • Up-to-date: Merges and releases new versions of Pyright within a day of an upstream release.
  3. Overview of re-implemented Pylance features

    main

    basedpyright re-implements several features that were previously exclusive to Microsoft's closed-source Pylance extension, making them available in any LSP-compatible editor:

    • Semantic Highlighting: Improved support, including Python 3.12 type keyword and Final variable coloring.
    • Inlay Hints: Includes support for double-clicking to insert hints, even for Callable types.
    • Docstrings for Builtins: Uses docify to include docstrings for compiled builtin functions/classes for all supported Python versions and platforms (macOS, Windows, Linux) within the default typeshed stubs.
    • Docstring Parsing: Fixed parsing of multi-line parameter descriptions in docstrings.
    • Refactoring: Supports renaming packages and modules.
    • Navigation: Supports "Go to Implementations" and "Go to Definition" (including hover information) on operators.
  4. Understand Pyright vs Mypy design differences

    main
    Pyright is designed for high performance (3x-5x faster than Mypy) and as a foundation for language servers. It uses a 'lazy' or 'just-in-time' type evaluator, allowing it to evaluate identifiers anywhere in a module without full top-to-bottom analysis. Pyright also implements its own parser that recovers gracefully from syntax errors, whereas Mypy uses the Python interpreter's parser and stops at syntax errors.
  5. Understand Python Scopes and Symbols

    main

    In Pyright, a symbol is any name that is not a keyword (e.g., classes, functions, variables, parameters). Symbols exist within scopes, which define visibility.

    Common scopes include:

    1. Builtins: The outermost scope (e.g., int, list).
    2. Module: The current source file.
    3. Class: Contains methods, class variables, and instance variables.
    4. Function/Lambda: Contains parameters and local variables.
    5. List Comprehensions: Define their own isolated scope.
  6. Understand the basedpyright code structure

    main

    The repository is organized into several packages that serve different entry points and environments:

    • packages/vscode-pyright/src/extension.ts: LSP client entry point for the VS Code extension.
    • packages/pyright-internal/src/pyright.ts: Main entry point for the command-line tool.
    • packages/pyright-internal/src/server.ts: Main entry point for the LSP server.
    • packages/pyright: The core basedpyright npm package.
    • packages/browser-pyright: A build of basedpyright designed to run in a browser.
    • basedpyright: The PyPI package wrapper for the npm package (allows usage without manual Node.js installation).
    • packages/pyright-internal/typeshed-fallback/: Contains recent copies of Typeshed type stub files for the Python stdlib.
    • docstubs: Generated stubs containing docstrings for compiled modules.

    Core logic for parsing and analysis is located in packages/pyright-internal/src/analyzer, packages/pyright-internal/src/parser, and packages/pyright-internal/src/common.

  7. Use the localization helper tool

    main

    A TUI (Terminal User Interface) tool is provided to assist with the localization process. It allows you to:

    • Check every message in comparison with the corresponding English message.
    • Compare message keys with the English version to identify missing or redundant messages.

    The interface is built with textual and supports mouse interaction:

    • Tabs: Click at the top to switch between different language localizations.
    • Function Buttons: Click at the bottom to perform operations.
    • Message Tree: Click a category to expand/collapse; click a message entry to automatically prompt the corresponding English entry.

    Note: If the "Compare message keys differences" operation is active, you can only close the popup by pressing the C key.

    # use uv
    ./gg.cmd uv run build/py_latest/localization_helper.py
    
    # or from inside the venv
    npm run localization-helper
  8. Enable the baseline feature

    main

    The baseline feature allows you to adopt new tools or enable new checks without being overwhelmed by existing errors. It tracks current errors in a baseline file and only reports errors in newly written or modified code.

    To enable baseline, generate the baseline file by running the following command in your terminal:

    basedpyright --writebaseline

    Alternatively, you can run the basedpyright: Write new errors to baseline task within your editor. This creates a file at ./.basedpyright/baseline.json. You should commit this file to your version control system.

  9. Use Pyright as a Language Server

    main

    Pyright functions as a language server to provide IDE-like features during development. Key capabilities include:

    • Intelligent Completion: Automatic completion of keywords, symbols, and import names.
    • Auto-Imports: Automatic insertion of import statements during type completion.
    • Signature Help: Tips for filling in function arguments.
    • Navigation: Find Definitions, Find References, and Find Symbols (within a document or workspace).
    • Refactoring: Rename Symbol across the codebase and Organize Imports (following PEP8).
    • Inspection: Hover over symbols for type information and docstrings, and view call hierarchies.
    • Stub Generation: Generate type stubs for third-party libraries.
  10. Best practices for type annotations in libraries

    main

    To provide a high-quality developer experience, follow these annotation patterns:

    • Use the widest possible types for inputs: Use Sequence[str] instead of list[str] or Mapping[str, int] instead of dict[str, int] to allow more flexible caller arguments.
    • Use @overload for multiple return types: Use the typing.overload mechanism when a function's return type depends on its input arguments.
    • Use keyword-only and positional-only parameters: Use * for keyword-only arguments and / for positional-only arguments to clarify the API.
    • Annotate decorators: If a decorator preserves the signature, use TypeVar and Callable. For complex signature mutations, consider ParamSpec and Concatenate (Python 3.10+).
    • Use Literal for specificity: Use Literal for specific allowed values instead of broad types.
    • Use Final for constants: Mark constants with Final to indicate they should not be reassigned.
  11. Work with Generic Types and Invariance

    main

    Generic types (like list[int]) use type arguments in square brackets to specify the type of their contents.

    Invariance in Mutable Containers

    Mutable container types (like list, dict, or set) are typically invariant. This means the type argument must match exactly. For example, you cannot assign a list[int] to a variable declared as list[int | None] because appending None to the latter would violate the type contract of the former.

    Resolving Errors with Immutable Counterparts

    To resolve assignability errors with mutable containers, switch to their immutable counterparts. Immutable types are generally more flexible with type arguments.

    Mutable TypeImmutable Type
    listSequence
    dictMapping
    setContainer
    n/atuple

    Example of resolving an invariance error by using Sequence instead of list:

    my_list_1: list[int] = [1, 2, 3]
    # my_list_2: list[int | None] = my_list_1  # Error due to invariance
    
    my_list_2: Sequence[int | None] = my_list_1  # No longer an error