Pylance Documentation

repository·main·Indexed 24 days ago

https://github.com/microsoft/pylance-release

A high-performance Python language server for Visual Studio Code powered by the Pyright typing engine. Provides advanced IntelliSense, type checking, and code analysis. Includes configuration guides for language server modes, type checking intensity, diagnostic scopes, virtual workspaces, and indexing for third-party libraries.

Tokens
135.6K
Snippets
337
Records
728
Agent score
83%

What's inside Pylance

  1. Overview of the Type Server Protocol (TSP)

    main

    The Type Server Protocol (TSP) is a JSON-RPC based protocol used to request Python analysis data from a type server. It provides access to protocol versions, snapshots, Python search paths, import resolution, and various type queries (computed, declared, and expected types).

    Key characteristics:

    • Data Shapes: Uses Language Server Protocol (LSP) conventions for Position, Range, and URI string representations.
    • Method Prefix: All TSP methods are prefixed with typeServer/.
    • Communication: Typically operates over stdio on a main JSON-RPC connection, with optional support for extra read-only connections via ipc.
  2. Pylance Documentation Index

    main

    The Pylance documentation index provides access to guides, settings references, and diagnostic rule explanations. It is organized into several key areas:

    How-To Guides

    Step-by-step instructions for common workflows including:

    • Auto-Import: Controlling suggestions and indexing.
    • Type Checking: CI integration, gradual strict adoption, and type narrowing techniques.
    • Environment & Dependencies: Managing Python environments (venv, conda, uv, poetry), dependency files (requirements.txt, pyproject.toml), and editable installs.
    • Workspace Configuration: Monorepo setup, extra paths glob resolution, and remote development (SSH, WSL, containers).
    • Troubleshooting: Reading logs, resolving unresolved imports, and fixing notebook issues.
    • Advanced Features: Using Copilot with Pylance MCP tools, handling generated code, and managing bundled third-party stubs.

    Settings Reference

    Detailed documentation for configuring Pylance behavior across several categories:

    • Core Settings
    • Import and Path Settings
    • File Scope Settings
    • Indexing and Completions
    • Code Actions and Hints
    • Editor and Typing
    • AI Features
    • Diagnostics Display
    • Type Evaluation Settings
  3. What is `python.analysis.indexing` and how does it work?

    main

    The python.analysis.indexing setting controls whether Pylance scans your codebase and installed third-party libraries to build a symbol index. This index powers advanced IntelliSense features by allowing Pylance to understand symbols that are not currently open in your editor.

    Key Benefits

    • Improved Auto-Imports: Suggests imports for symbols that are neither imported nor currently open in VS Code.
    • Enhanced Code Navigation: Improves the performance and scope of the go to symbol feature across the entire workspace.
    • Improved Code Generation: Automatically adds import statements for used symbols during code generation.

    Performance Trade-offs

    Indexing consumes CPU and memory. For very large projects or resource-constrained environments (like remote development), disabling indexing can improve editor responsiveness.

  4. What is type narrowing and how to use it

    main

    Type narrowing is a technique used to resolve type errors when working with union types (e.g., str | None or int | str). When a variable has multiple possible types, Pylance cannot guarantee which one is active. You can use conditional checks to 'narrow' the type, telling Pylance exactly which variant you are working with in a specific code branch.

    Narrowing works in both if and else branches. For example, if you check isinstance(val, int), Pylance treats val as an int inside the if block and as the remaining types in the else block.

    def describe(val: int | str):
        if isinstance(val, int):
            print(val + 1)      # OK — val is int here
        else:
            print(val.upper())  # OK — val is str here
  5. Understand the `reportIndexIssue` diagnostic

    main
    The reportIndexIssue diagnostic in Pylance and Pyright identifies errors related to indexing or subscripting objects. It triggers when you attempt to use an invalid index type (e.g., using an int to index a dict[str, int]) or when you attempt to subscript an object that does not support indexing (e.g., an int). This diagnostic is designed to catch type errors and incorrect usage of lists, tuples, dictionaries, and other indexable types.
  6. Understand the reportTypeCommentUsage diagnostic

    main
    The reportTypeCommentUsage diagnostic flags instances where type comments (e.g., # type: ...) are used in ways that are deprecated or not recommended. This diagnostic is designed to encourage the use of modern Python type annotation syntax (PEP 526 / PEP 3107) and ensure compatibility with static type checkers. Type comments were primarily used for Python 2 compatibility but are considered deprecated in modern Python (3.6+).
  7. Manage Indexing for Performance

    main

    Indexing pre-parses workspace files and library packages to enable fast auto-imports, workspace symbol search (Ctrl+T), and completions. This involves an upfront trade-off in CPU and memory usage.

    Key Indexing Settings

    SettingEffect
    python.analysis.indexingtrue (default) enables background indexing; false disables it
    python.analysis.userFileIndexingLimitMaximum number of user files to index (default: 2000; -1 for unlimited)
    python.analysis.packageIndexDepthsControls how deep Pylance indexes specific third-party packages
    python.analysis.includeVenvInWorkspaceSymbolsInclude venv site-packages symbols in workspace symbol search (default: false)
    python.analysis.includeExtraPathSymbolsInSymbolSearchInclude extraPaths symbols in workspace symbol search (default: false)

    When to Disable Indexing

    Set "python.analysis.indexing": false if:

    • Startup is too slow and you can tolerate reduced auto-import coverage.
    • You primarily work in open files and do not rely on workspace symbol search.
    • Memory usage is a concern on constrained machines.

    Note: Without indexing, auto-imports still work for open files, their transitive imports, and the stdlib, but will not find symbols in files that haven't been loaded.

  8. Understand Pylance configuration precedence

    main

    Pylance resolves settings from multiple sources. If a setting is not behaving as expected, a higher-priority source is likely overriding it. The precedence order (from highest to lowest) is:

    1. pyrightconfig.json or pyproject.toml [tool.pyright] section (Per-project)
    2. .vscode/settings.json (Workspace folder)
    3. .code-workspace file settings (Per-workspace)
    4. User settings (settings.json) (Global)
    5. languageServerMode defaults (Implicit defaults)

    Note on Config Files: If both pyrightconfig.json and pyproject.toml (with [tool.pyright]) exist in a workspace, pyrightconfig.json takes precedence and pyproject.toml is ignored.

  9. Relationship between `indexing` and `persistAllIndices`

    main

    It is important to distinguish between these two settings:

    1. python.analysis.indexing: A master toggle. It determines whether Pylance performs indexing of user files and third-party libraries at all. If false, indexing features are disabled.
    2. python.analysis.persistAllIndices: A performance optimization. It determines whether the indices created by the indexing process are saved to disk for reuse.

    If python.analysis.indexing is false, python.analysis.persistAllIndices does nothing.

  10. Understanding Standard Library Indices in Pylance

    main

    Pylance uses indices to provide fast code completions, auto-import suggestions, and symbol searches.

    By default, Pylance uses prebuilt indices to avoid the overhead of indexing the standard library every time a workspace is opened. However, these prebuilt indices are optimized for the latest Python version and may not account for:

    • Older Python versions (where certain modules or decorators do not exist).
    • Platform-specific modules (differences between Windows, Linux, etc.).

    Enabling python.analysis.regenerateStdLibIndices creates workspace-specific indices that accurately reflect your configured Python environment.