Top Related Projects
Static Type Checker for Python
Optional static typing for Python
Awesome autocompletion, static analysis and refactoring library for python
Fork of the python-language-server project, maintained by the Spyder IDE team and the community
Quick Overview
Pylance is a fast and feature-rich language server for Python, designed to work with Visual Studio Code. It provides advanced language features such as auto-imports, type checking, and intelligent code completion, enhancing the Python development experience in VS Code.
Pros
- Improved performance and responsiveness compared to other Python language servers
- Advanced type checking and inference capabilities
- Seamless integration with Visual Studio Code
- Regular updates and active development by Microsoft
Cons
- Limited to Visual Studio Code, not available for other editors
- Some features require a paid Visual Studio Code license
- Occasional false positives in type checking
- May have conflicts with other Python extensions
Getting Started
- Install Visual Studio Code
- Open VS Code and navigate to the Extensions view (Ctrl+Shift+X)
- Search for "Pylance" and click "Install"
- Open a Python file, and Pylance will automatically activate
- Configure Pylance settings in VS Code's settings.json file:
{
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic"
}
- Enjoy enhanced Python development with Pylance's features!
Competitor Comparisons
Static Type Checker for Python
Pros of pyright
- Open-source and fully transparent codebase
- Can be used as a standalone command-line tool
- More flexible configuration options for advanced users
Cons of pyright
- Less user-friendly for beginners
- Fewer built-in features compared to Pylance
- Requires more manual setup and configuration
Code comparison
Pyright configuration (pyrightconfig.json):
{
"include": ["src"],
"exclude": ["**/node_modules", "**/__pycache__"],
"strict": ["src/core"],
"reportMissingImports": true
}
Pylance configuration (settings.json):
{
"python.analysis.typeCheckingMode": "basic",
"python.analysis.diagnosticMode": "workspace",
"python.analysis.autoImportCompletions": true
}
Pyright is the core type-checking engine that powers Pylance. While Pyright offers more granular control and can be used independently, Pylance provides a more integrated and user-friendly experience within Visual Studio Code. Pylance includes additional features like auto-imports, type completion, and performance optimizations. However, it's not open-source like Pyright. The choice between the two depends on the user's needs, with Pyright being better suited for advanced users who require more control, and Pylance offering a more polished experience for general Python development in VS Code.
Optional static typing for Python
Pros of mypy
- Open-source and community-driven development
- More extensive type checking capabilities, including generics and union types
- Supports gradual typing, allowing incremental adoption in existing projects
Cons of mypy
- Slower performance compared to Pylance, especially for large codebases
- Less seamless integration with IDEs and editors outside of specific plugins
- May require more manual type annotations to achieve full coverage
Code Comparison
mypy:
from typing import List, Optional
def greet(names: List[str]) -> None:
for name in names:
print(f"Hello, {name}!")
def find_user(user_id: int) -> Optional[str]:
# Implementation
Pylance:
def greet(names: list[str]) -> None:
for name in names:
print(f"Hello, {name}!")
def find_user(user_id: int) -> str | None:
# Implementation
Both tools support type checking, but mypy uses the typing
module for annotations, while Pylance leverages newer Python syntax for type hints. Pylance also provides additional features like auto-imports and refactoring support, which are not part of mypy's core functionality.
Awesome autocompletion, static analysis and refactoring library for python
Pros of Jedi
- Open-source and community-driven development
- Lightweight and fast performance
- Language-server protocol support for integration with various editors
Cons of Jedi
- Less comprehensive type inference compared to Pylance
- Slower update cycle for new Python features
- Limited support for some advanced language features
Code Comparison
Jedi:
import jedi
script = jedi.Script("import os\nos.p")
completions = script.complete(1, 4)
print(completions[0].name) # Outputs: path
Pylance:
# Pylance is integrated into VS Code and doesn't require explicit code
# for basic functionality. It provides inline type information and
# autocompletion automatically.
Jedi is an open-source Python autocompletion and static analysis library, while Pylance is a Microsoft-developed language server for Python, primarily used in Visual Studio Code. Jedi offers a more lightweight solution with broad editor support, but Pylance provides more advanced features and tighter integration with VS Code. Pylance leverages Microsoft's Pyright type checker, offering superior type inference and faster performance for large codebases. However, Jedi's open-source nature allows for community contributions and use in various environments beyond VS Code.
Fork of the python-language-server project, maintained by the Spyder IDE team and the community
Pros of python-lsp-server
- Open-source and community-driven, allowing for greater customization and contributions
- Supports multiple Python versions and environments
- Integrates with various text editors and IDEs beyond Visual Studio Code
Cons of python-lsp-server
- Generally slower performance compared to Pylance
- Less comprehensive type checking and inference capabilities
- May require more manual configuration for optimal functionality
Code Comparison
python-lsp-server configuration example:
{
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.pycodestyleEnabled": true,
"python.linting.flake8Enabled": true
}
Pylance configuration example:
{
"python.analysis.typeCheckingMode": "basic",
"python.analysis.diagnosticMode": "workspace",
"python.analysis.autoImportCompletions": true
}
Both Pylance and python-lsp-server aim to provide language server functionality for Python, offering features like code completion, linting, and type checking. Pylance, developed by Microsoft, is optimized for Visual Studio Code and offers faster performance and more advanced type inference. python-lsp-server, on the other hand, is a community-driven project that provides greater flexibility and compatibility with various editors, but may require more setup and offer less advanced features in some areas.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Pylance
Fast, feature-rich language support for Python
This repository is for providing feedback and documentation on the Pylance language server extension in Visual Studio Code. You can use the repository to report issues or submit feature requests. The Pylance codebase is not open-source but you can contribute to Pyright to make improvements to the core typing engine that powers the Pylance experience.
Pylance is the default language support for Python in Visual Studio Code and is shipped as part of that extension as an optional dependency.
Quick Start
- Install the Python extension from the marketplace. Pylance will be installed as an optional extension.
- Open a Python (.py) file and the Pylance extension will activate.
Note: If you've previously set a language server and want to try Pylance, make sure you've set "python.languageServer": "Default" or "Pylance"
in your settings.json file using the text editor, or using the Settings Editor UI.
Features
<img src=images/all-features.gif>
Pylance provides some awesome features for Python 3, including:
- Docstrings
- Signature help, with type information
- Parameter suggestions
- Code completion
- Auto-imports (as well as add and remove import code actions)
- As-you-type reporting of code errors and warnings (diagnostics)
- Code outline
- Code navigation
- Type checking mode
- Native multi-root workspace support
- IntelliCode compatibility
- Jupyter Notebooks compatibility
- Semantic highlighting
See the changelog for the latest release.
Settings and Customization
Pylance provides users with the ability to customize their Python language support via a host of settings which can either be placed in the settings.json
file in your workspace, or edited through the Settings Editor UI.
-
python.analysis.languageServerMode
-
Offers predefined configurations to help users optimize Pylance's performance based on their development needs. It controls how many IntelliSense features Pylance provides, allowing you to choose between full language service functionality or a lightweight experience optimized for performance.
-
Default value:
default
-
Available values:
light
default
(default)full
-
Description:
default
: Provides a balanced experience with many useful features enabled by default. It ensures that the language server delivers sufficient functionality for most users without overloading the system. Advanced features can be enabled as needed, allowing for further customization at the cost of performance.light
: Designed for users seeking a lightweight, memory-efficient setup. This mode disables various features to make Pylance function more like a streamlined text editor. Ideal for those who do not require the full breadth of IntelliSense capabilities and prefer Pylance to be as resource-friendly as possible.full
: Designed for users seeking the most extensive feature set. This mode enables most of Pylance's features, offering the richest IntelliSense experience. Ideal for those who want access to the full range of available functionality.
-
Individual settings can be configured to override the defaults set by
languageServerMode
. -
Default settings based on mode are:
Mode light default full python.analysis.exclude ["**"] [] [] python.analysis.useLibraryCodeForTypes false true true python.analysis.enablePytestSupport false true true python.analysis.indexing false true true python.analysis.autoImportCompletions false false true python.analysis.showOnlyDirectDependenciesInAutoImport false false true python.analysis.packageIndexDepths See settings below python.analysis.regenerateStdLibIndices false false true python.analysis.userFileIndexingLimit 2000 2000 -1 python.analysis.includeAliasesFromUserFiles false false true python.analysis.functionReturnTypes false false true python.analysis.pytestParameters false false true python.analysis.supportRestructuredText false false true python.analysis.supportDocstringTemplate false false true
-
-
python.analysis.typeCheckingMode
- Used to specify the level of type checking analysis performed.
- Default:
off
.Note that the value of this setting can be overridden by having a pyrightconfig.json or a pyproject.toml. For more information see this link.
- Available values:
off
: No type checking analysis is conducted; unresolved imports/variables diagnostics are producedbasic
: Alloff
rules + basic type checking rulesstandard
: Alloff
rules + basic type checking rules + standard type checking rulesstrict
: Alloff
rules + all type checking rules.
- Performance Consideration:
- Setting
python.analysis.typeCheckingMode
tooff
can improve performance by disabling type checking analysis, which can be resource-intensive, especially in large codebases.
- Setting
-
python.analysis.diagnosticMode
- Used to allow a user to specify what files they want the language server to analyze to get problems flagged in their code.
- Available values:
workspace
openFilesOnly
(default)
- Performance Consideration:
- Setting
python.analysis.diagnosticMode
toopenFilesOnly
limits analysis to open files, improving performance by reducing the amount of code Pylance needs to process in large workspaces.
- Setting
-
python.analysis.include
- Paths of directories or files that should be included. If no paths are specified, Pylance defaults to the directory that contains workspace root. Paths may contain wildcard characters
**
(a directory or multiple levels of directories),*
(a sequence of zero or more characters), or?
(a single character). - Default value: empty array
- Paths of directories or files that should be included. If no paths are specified, Pylance defaults to the directory that contains workspace root. Paths may contain wildcard characters
-
python.analysis.exclude
- Paths of directories or files that should not be included. These override the include directories, allowing specific subdirectories to be excluded. Note that files in the exclude paths may still be included in the analysis if they are referenced (imported) by source files that are not excluded. Paths may contain wildcard characters
**
(a directory or multiple levels of directories),*
(a sequence of zero or more characters), or?
(a single character). If no exclude paths are specified, Pylance automatically excludes the following:**/node_modules
,**/__pycache__
,.git
and any virtual environment directories. - Default value: empty array (or
["**"]
inlight
mode) - Performance Consideration:
- Excluding unnecessary files or directories can significantly improve performance by reducing the scope of analysis. For example, setting
python.analysis.exclude
to["**"]
will exclude all files except those currently open, minimizing resource consumption.
- Excluding unnecessary files or directories can significantly improve performance by reducing the scope of analysis. For example, setting
- Paths of directories or files that should not be included. These override the include directories, allowing specific subdirectories to be excluded. Note that files in the exclude paths may still be included in the analysis if they are referenced (imported) by source files that are not excluded. Paths may contain wildcard characters
-
python.analysis.ignore
- Paths of directories or files whose diagnostic output (errors and warnings) should be suppressed even if they are an included file or within the transitive closure of an included file. Paths may contain wildcard characters
**
(a directory or multiple levels of directories),*
(a sequence of zero or more characters), or?
(a single character). - Default value: empty array
- Paths of directories or files whose diagnostic output (errors and warnings) should be suppressed even if they are an included file or within the transitive closure of an included file. Paths may contain wildcard characters
-
python.analysis.stubPath
- Used to allow a user to specify a path to a directory that contains custom type stubs. Each package's type stub file(s) are expected to be in its own subdirectory.
- Default value:
./typings
-
python.analysis.autoSearchPaths
- Used to automatically add search paths based on some predefined names (like
src
). - Available values:
true
(default)false
- Used to automatically add search paths based on some predefined names (like
-
python.analysis.extraPaths
- Used to specify extra search paths for import resolution. This replaces the old
python.autoComplete.extraPaths
setting. - Default value: empty array
- Used to specify extra search paths for import resolution. This replaces the old
-
python.analysis.diagnosticSeverityOverrides
- Used to allow a user to override the severity levels for individual diagnostics should they desire.
- Accepted severity values:
error
(red squiggle)warning
(yellow squiggle)information
(blue squiggle)none
(disables the rule)
- Available rules to use as keys can be found here
- Example:
{ "python.analysis.diagnosticSeverityOverrides": { "reportUnboundVariable": "information", "reportImplicitStringConcatenation": "warning" } }
-
python.analysis.typeEvaluation
- Used to allow a user to override the behavior of type evaluator should they desire.
- Available rules to use as subkeys can be found here
- Example:
{ "python.analysis.typeEvaluation.enableReachabilityAnalysis": true, "python.analysis.typeEvaluation.strictDictionaryInference": false }
-
python.analysis.disableTaggedHints
- Disable hint diagnostics with special hints for grayed-out or strike-through text.
- Accepted values:
true
false
(default)
-
python.analysis.useLibraryCodeForTypes
- Used to parse the source code for a package when a typestub is not found.
- Default value:
true
(orfalse
inlight
mode) - Accepted values:
true
(default)false
- Performance Consideration:
- Setting
python.analysis.useLibraryCodeForTypes
tofalse
can improve performance by preventing Pylance from parsing the source code of third-party libraries when type stubs are unavailable, thereby reducing resource usage.
- Setting
-
- Used to specify whether Pylance should index installed third party libraries and user files to improve features such as auto-import, add import, workspace symbols, etc.
- Without indexing, auto-import, add import, and workspace symbols will have less information.
- Default value:
true
(orfalse
inlight
mode) - Available values:
true
(default)false
- Performance Consideration:
- Disabling indexing by setting
python.analysis.indexing
tofalse
can improve performance by reducing resource consumption, especially in large projects, at the cost of making features like auto-imports and workspace symbol search find fewer symbols.
- Disabling indexing by setting
-
python.analysis.userFileIndexingLimit
- Maximum number of user files to index in the workspace. Indexing files is a performance-intensive task. Please use this setting to limit the number of files you want us to index. If you enter -1, we will index all files.
- Default value: 2000 (or -1 for
full
mode) - Performance Consideration:
- Increasing this number will cause Pylance to allocate more resources for user file indexing.
-
python.analysis.packageIndexDepths
- Used to override how many levels under installed packages to index on a per package basis. By default, only top-level modules are indexed (depth = 1). To index submodules, increase depth by 1 for each level of submodule you want to index.
- Default value:
or in[ { "name": "sklearn", "depth": 2 }, { "name": "matplotlib", "depth": 2 }, { "name": "scipy", "depth": 2 }, { "name": "django", "depth": 2 }, { "name": "flask", "depth": 2 }, { "name": "fastapi", "depth": 2 } ]
full
mode[ { "name": "", "depth": 4, "includeAllSymbols": true } ]
- Accepted values:
If{ "name": "package name (str)", "depth": "depth to scan (int)", "includeAllSymbols": "whether to include all symbols (bool)" }
includeAllSymbols
is set tofalse
, only symbols in each package's__all__
are included. When it's set totrue
, Pylance will index every module/top level symbol declarations in the file. - Example:
[ { "name": "sklearn", "depth": 2, "includeAllSymbols": true }, { "name": "matplotlib", "depth": 3, "includeAllSymbols": false } ]
- Performance Consideration:
- Adjusting this setting will cause Pylance to allocate more resources for indexing third-party libraries.
-
python.analysis.regenerateStdLibIndices
- Instead of relying on the shared
stdlib.json
indices for all Python versions, generate unique indices tailored to each workspace's specific Python version and platform. This regeneration process will affect performance, unlike using the prebuilt stdlib indices. - Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Performance Consideration:
- Enabling this can impact performance by creating its own indices for standard libraries.
- Instead of relying on the shared
-
python.analysis.includeAliasFromUserFiles
- Include alias symbols from user files. This will make alias symbols appear in features such as
add import
andauto import
. - Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Performance Consideration:
- Enabling this can impact performance by increasing the number of completion items and indexing multiple files as changes occur.
- Include alias symbols from user files. This will make alias symbols appear in features such as
-
python.analysis.autoImportCompletions
- Used to control the offering of auto-imports in completions. This will impact number of items shown in the completion and performance.
- Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Performance Consideration:
- Enabling
python.analysis.autoImportCompletions
can impact performance by increasing the number of completion items and resource usage. Disabling it can improve performance by reducing the computational overhead during code completion.
- Enabling
-
python.analysis.showOnlyDirectDependenciesInAutoImport
- Show only direct dependencies declared in
requirements.txt
orpyproject.toml
inauto import
suggestions, if they exist. This only affectsauto import
for completions. Theadd import
code action will continue to show all possible imports. - Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Show only direct dependencies declared in
-
python.analysis.importFormat
- Defines the default format for import module.
- Accepted values:
absolute
(default)relative
-
python.analysis.completeFunctionParens
- Add parentheses to function completions.
- Accepted values:
true
false
(default)
- Performance Consideration:
- Disabling
python.analysis.completeFunctionParens
can slightly improve performance by reducing the overhead during code completion, though the impact is minimal.
- Disabling
-
python.analysis.inlayHints.variableTypes
- Enable/disable inlay hints for variable types.
- Accepted values:
true
false
(default)
- Performance Consideration:
- Disabling inlay hints for variable types by setting
python.analysis.inlayHints.variableTypes
tofalse
can improve performance by reducing the processing required to generate these hints, which can be beneficial in large codebases.
- Disabling inlay hints for variable types by setting
-
python.analysis.inlayHints.functionReturnTypes
- Enable/disable inlay hints for function return types.
- Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Performance Consideration:
- Disabling inlay hints for function return types can improve performance by reducing the overhead of generating these hints.
-
python.analysis.inlayHints.callArgumentNames
- Enable/disable inlay hints for call argument names.
- Accepted values:
off
(default)partial
all
- Performance Consideration:
- Setting
python.analysis.inlayHints.callArgumentNames
tooff
can improve performance by reducing the processing needed to display argument names during function calls.
- Setting
-
python.analysis.inlayHints.pytestParameters
- Enable/disable inlay hints for pytest function parameters.
- Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Example:
becomesdef test_foo(my_fixture): assert(my_fixture)
def test_foo(my_fixture: str): assert(my_fixture)
- Performance Consideration:
- Disabling inlay hints for pytest parameters can improve performance by reducing the overhead associated with generating these hints.
-
python.analysis.fixAll
- The set of commands to run when doing a
fixall
. - Accepted values:
source.unusedImports
source.convertImportFormat
- The set of commands to run when doing a
-
python.analysis.enablePytestSupport
- Enable pytest goto def and inlay hint support for fixtures.
- Default value:
true
(orfalse
inlight
mode) - Accepted values:
true
(default)false
- Performance Consideration:
- Disabling pytest support by setting
python.analysis.enablePytestSupport
tofalse
can improve performance by reducing the overhead associated with providing IntelliSense features for pytest fixtures.
- Disabling pytest support by setting
-
python.analysis.autoFormatStrings
- When typing a
{
in a string, automatically puts anf
on the front of the string. - Accepted values:
true
false
(default)
- Performance Consideration:
- Disabling
python.analysis.autoFormatStrings
can slightly improve performance by reducing the processing required during string formatting, though the impact is minimal.
- Disabling
- When typing a
-
python.analysis.nodeExecutable
- Path to a node executable to use to run Pylance. If this value is empty, Pylance uses VS Code's node executable.
- Set this value when you are having out of memory issues. Using a custom node executable allows Pylance to allocate more memory.
- Accepted values:
any executable path
-
python.analysis.autoIndent
- Automatically adjust indentation based on language semantics when typing Python code.
- Accepted values:
true
(default)false
-
python.analysis.supportRestructuredText
- Enable/disable support for reStructuredText in docstrings. Experimental, may cause docstrings to no longer render.
- Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Performance Consideration:
- Disabling support for reStructuredText in docstrings by setting
python.analysis.supportRestructuredText
tofalse
can improve performance by reducing the overhead of parsing complex docstrings.
- Disabling support for reStructuredText in docstrings by setting
-
python.analysis.aiCodeActions
- Enable/disable AI-assisted code actions. Requires the Copilot Chat extension to be enabled.
- Accepted values:
true
false
(default)
- Available code actions to use as keys:
implementAbstractClasses
. - Example:
{ "python.analysis.aiCodeActions": { "implementAbstractClasses": true } }
-
python.analysis.supportDocstringTemplate
- Enable/disable support for docstring generation.
- Default value:
false
(ortrue
infull
mode) - Accepted values:
true
false
(default)
- Example:
def foo(arg): """ |<Trigger completions here """
-
python.analysis.displayEnglishDiagnostics
- Display diagnostics in English regardless of VS Code's display language.
- Accepted values:
true
false
(default)
Semantic highlighting
Visual Studio Code uses TextMate grammars as the main tokenization engine. TextMate grammars work on a single file as input and break it up based on lexical rules expressed in regular expressions.
Semantic tokenization allows language servers to provide additional token information based on the language server's knowledge on how to resolve symbols in the context of a project. Themes can opt-in to use semantic tokens to improve and refine the syntax highlighting from grammars. The editor applies the highlighting from semantic tokens on top of the highlighting from grammars.
Here's an example of what semantic highlighting can add:
Without semantic highlighting:
With semantic highlighting:
Semantic colors can be customized in settings.json by associating the Pylance semantic token types and modifiers with the desired colors.
-
Semantic token types
- class, enum
- parameter, variable, property, enumMember
- function, member
- module
- intrinsic
- magicFunction (dunder methods)
- selfParameter, clsParameter
-
Semantic token modifiers
- declaration
- readonly, static, abstract
- async
- typeHint, typeHintComment
- decorator
- builtin
The scope inspector tool allows you to explore what semantic tokens are present in a source file and what theme rules they match to.
Example of customizing semantic colors in settings.json:
{
"editor.semanticTokenColorCustomizations": {
"[One Dark Pro]": {
// Apply to this theme only
"enabled": true,
"rules": {
"magicFunction:python": "#ee0000",
"function.declaration:python": "#990000",
"*.decorator:python": "#0000dd",
"*.typeHint:python": "#5500aa",
"*.typeHintComment:python": "#aaaaaa"
}
}
}
}
Source Code Actions
-
source.unusedImports
- Remove all unused imports in a file
-
source.convertImportFormat
- Convert import format according to
python.analysis.importFormat
.
- Convert import format according to
-
source.fixall.pylance
- Apply the commands listed in the
python.analysis.fixall
setting
- Apply the commands listed in the
Troubleshooting
Known issues are documented in TROUBLESHOOTING.
Contributing
Pylance leverages Microsoft's open-source static type checking tool, Pyright, to provide performant language support for Python.
Code contributions are welcomed via the Pyright repo.
Pylance ships with a collection of type stubs for popular modules to provide fast and accurate auto-completions and type checking. Our type stubs are sourced from typeshed and our work-in-progress stub repository, microsoft/python-type-stubs. Type stubs in microsoft/python-type-stubs will be contributed back to typeshed or added inline to source packages once they are of high enough quality.
For information on getting started, refer to the CONTRIBUTING instructions.
Feedback
- File a bug in GitHub Issues
- Tweet us with other feedback
License
See LICENSE for more information.
Top Related Projects
Static Type Checker for Python
Optional static typing for Python
Awesome autocompletion, static analysis and refactoring library for python
Fork of the python-language-server project, maintained by the Spyder IDE team and the community
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot