### Install Dependencies with pw uv sync Source: https://docs.basedpyright.com/latest/development/contributing Run this command to install all project dependencies, including pyprojectx, uv, node, and typescript. Dependencies are installed locally. ```bash ./pw uv sync ``` -------------------------------- ### Example Output of Version Check Source: https://docs.basedpyright.com/latest/development/upstream This is an example of the output you will see when running the `basedpyright --version` command, indicating the Pyright version. ```text basedpyright 1.14.0 based on pyright 1.1.372 ``` -------------------------------- ### Install basedpyright globally with uv Source: https://docs.basedpyright.com/latest/installation/command-line-and-language-server Install the basedpyright tool globally using the uv package manager. This makes the basedpyright command available system-wide. ```bash uv tool install basedpyright ``` -------------------------------- ### Setup BasedPyright LSP in Neovim (0.10 Legacy) Source: https://docs.basedpyright.com/latest/installation/ides For older Neovim versions (0.10 and below), use this configuration with `nvim-lspconfig` to set up the BasedPyright language server. ```lua local lspconfig = require("lspconfig") lspconfig.basedpyright.setup{} ``` -------------------------------- ### Install basedpyright with npm Source: https://docs.basedpyright.com/latest/installation/command-line-and-language-server Install the basedpyright npm package. This method is intended for users who cannot use the pypi package, such as those on unsupported operating systems or older Python versions. ```bash npm install basedpyright ``` -------------------------------- ### Baseline File Update Example Source: https://docs.basedpyright.com/latest/configuration/command-line Demonstrates the output when basedpyright updates the baseline file. Shows the number of errors updated and the final error count. ```bash >basedpyright updated ./.basedpyright/baseline.json with 200 errors (went down by 5) 0 errors, 0 warnings, 0 notes ``` -------------------------------- ### Install basedpyright with pip Source: https://docs.basedpyright.com/latest/installation/command-line-and-language-server Install the basedpyright package using pip. This is a standard method for installing Python packages. ```bash pip install basedpyright ``` -------------------------------- ### Display basedpyright help Source: https://docs.basedpyright.com/latest/installation/command-line-and-language-server Run the basedpyright command with the --help flag to display command-line usage instructions. This is useful after installation to verify the CLI is accessible and to learn about its options. ```bash basedpyright --help ``` -------------------------------- ### Install Basedpyright Prek Hook Source: https://docs.basedpyright.com/latest/installation/prek-hook Configure your .pre-commit-config.yaml to use the basedpyright prek hook. Ensure you specify the correct repository and revision. ```yaml repos: - repo: https://github.com/DetachHead/basedpyright-prek-mirror rev: 1.39.3 hooks: - id: basedpyright ``` -------------------------------- ### Install basedpyright with Homebrew Source: https://docs.basedpyright.com/latest/installation/command-line-and-language-server Install basedpyright using the Homebrew package manager on macOS or Linux. This is a convenient option for users who manage their packages with Homebrew. ```bash brew install basedpyright ``` -------------------------------- ### Configure Basedpyright Settings in Neovim (Legacy 0.10) Source: https://docs.basedpyright.com/latest/configuration/language-server-settings Set up the Basedpyright language server in Neovim version 0.10 using the legacy `setup` function. This configures diagnostic mode and inlay hints. ```lua require("lspconfig").basedpyright.setup { settings = { basedpyright = { analysis = { diagnosticMode = "openFilesOnly", inlayHints = { callArgumentNames = true } } } } } ``` -------------------------------- ### Call-Site Return Type Inference Example Source: https://docs.basedpyright.com/latest/usage/type-inference Demonstrates how Pyright infers return types based on argument types passed during function calls. This can be applied recursively. ```python def func1(a, b, c): if c: return a elif c > 3: return b else: return None ``` ```python def func2(p_int: int, p_str: str, p_flt: float): # The type of var1 is inferred to be `int | None` based # on call-site return type inference. var1 = func1(p_int, p_int, p_int) # The type of var2 is inferred to be `str | float | None`. var2 = func1(p_str, p_flt, p_int) ``` -------------------------------- ### Configure Basedpyright Settings in Neovim (0.11+) Source: https://docs.basedpyright.com/latest/configuration/language-server-settings Configure Basedpyright analysis and inlay hints settings for Neovim version 0.11 and later using Lua. This example sets diagnostic mode and enables call argument names for inlay hints. ```lua return { settings = { basedpyright = { analysis = { diagnosticMode = "openFilesOnly", inlayHints = { callArgumentNames = true } } } } } ``` -------------------------------- ### Configure Basedpyright Settings in Helix Source: https://docs.basedpyright.com/latest/configuration/language-server-settings Configure the Basedpyright language server in Helix using the `languages.toml` file. This example sets the diagnostic mode. ```toml [language-server.basedpyright] command = "basedpyright-langserver" args = ["--stdio"] [language-server.basedpyright.config] basedpyright.analysis.diagnosticMode = "openFilesOnly" ``` -------------------------------- ### Check Basedpyright Version Source: https://docs.basedpyright.com/latest/development/upstream Run this command to determine which Pyright version your basedpyright installation is based on. ```bash basedpyright --version ``` -------------------------------- ### Set Diagnostic Levels Source: https://docs.basedpyright.com/latest/configuration/comments Configure the severity level for specific diagnostics directly within the file. This example sets 'reportPrivateUsage' to 'warning' and 'reportOptionalCall' to 'error'. ```python # pyright: reportPrivateUsage=warning, reportOptionalCall=error ``` -------------------------------- ### Add basedpyright to dev dependencies with uv Source: https://docs.basedpyright.com/latest/installation/command-line-and-language-server Install basedpyright as a development dependency using the uv package manager. This is the recommended approach for Python projects. ```bash uv add --dev basedpyright ``` -------------------------------- ### Install basedpyright with conda Source: https://docs.basedpyright.com/latest/installation/command-line-and-language-server Install basedpyright using the conda package manager from the conda-forge channel. This is an alternative for users within the conda ecosystem. ```bash conda install conda-forge::basedpyright ``` -------------------------------- ### Invalid Pyright Configuration Example Source: https://docs.basedpyright.com/latest/benefits-over-pyright/errors-on-invalid-configuration This TOML configuration demonstrates an incorrect setting for Pyright's mode. Basedpyright will detect this invalid configuration and report an error. ```toml [tool.pyright] mode = "strict" # wrong! the setting you're looking for is called `typeCheckingMode` ``` -------------------------------- ### Bidirectional Type Inference Examples Source: https://docs.basedpyright.com/latest/usage/type-inference Demonstrates how explicit type annotations on the left-hand side influence the inferred type of the right-hand side in assignments. ```python var1 = [] # Type of RHS is ambiguous var2: list[int] = [] # Type of LHS now makes type of RHS unambiguous var3 = [4] # Type is assumed to be list[int] var4: list[float] = [4] # Type of RHS is now list[float] var5 = (3,) # Type is assumed to be tuple[Literal[3]] var6: tuple[float, ...] = (3,) # Type of RHS is now tuple[float, ...] ``` -------------------------------- ### Configure Basedpyright Diagnostic Mode in VS Code Source: https://docs.basedpyright.com/latest/configuration/language-server-settings Set the diagnostic mode for the Basedpyright language server in VS Code's settings.json. This example sets it to 'openFilesOnly'. ```json { "basedpyright.analysis.diagnosticMode": "openFilesOnly" } ``` -------------------------------- ### GitLab CI Configuration for Code Quality Report Source: https://docs.basedpyright.com/latest/configuration/command-line Example of how to configure GitLab CI to use basedpyright for code quality reports. Specifies the script command and artifact reporting. ```yaml basedpyright: script: basedpyright --gitlabcodequality report.json artifacts: reports: codequality: report.json ``` -------------------------------- ### Multi-Assignment Type Inference Examples Source: https://docs.basedpyright.com/latest/usage/type-inference Shows how Pyright infers the type of a symbol when it is assigned values of different types in multiple locations. The inferred type becomes a union of all assigned types. ```python # In this example, symbol var1 has an inferred type of `str | int`. class Foo: def __init__(self): self.var1 = "" def do_something(self, val: int): self.var1 = val # In this example, symbol var2 has an inferred type of `Foo | None`. if __debug__: var2 = None else: var2 = Foo() ``` -------------------------------- ### Static Conditional Evaluation Examples Source: https://docs.basedpyright.com/latest/usage/type-concepts-advanced Pyright statically evaluates conditional expressions involving version info, platform, type checking flags, boolean literals, defined constants, and logical operators. ```python # sys.version_info # sys.version_info[0] >= # sys.platform == # os.name == # typing.TYPE_CHECKING or typing_extensions.TYPE_CHECKING # True or False # An identifier defined with the "defineConstant" configuration option # A `not` unary operator with any of the above forms # An `and` or `or` binary operator with any of the above forms ``` -------------------------------- ### Configure Basedpyright Config File Path in Neovim for Monorepos Source: https://docs.basedpyright.com/latest/configuration/language-server-settings Set the Basedpyright configuration file path in Neovim for monorepo projects. This uses Lua and dynamically gets the current working directory. ```lua return { settings = { basedpyright = { analysis = { configFilePath = vim.fn.getcwd() .. "/backend" } } } } ``` -------------------------------- ### Basedpyright Limitation: Multi-level Initialization Calls Source: https://docs.basedpyright.com/latest/benefits-over-pyright/improved-reportUninitializedInstanceVariable This example demonstrates a limitation in basedpyright's current implementation. It only checks one call deep from `__init__`. Since `__init__` calls `initialize`, which then calls `reset`, basedpyright still reports an error for `self.x` not being initialized, even though it would be initialized in practice. ```python class A: x: int # reportUninitializedInstanceVariable error def __init__(self) -> None: self.initialize() def initialize(self): self.reset() def reset(self): self.x = 3 ``` -------------------------------- ### Single-Assignment Type Inference Examples Source: https://docs.basedpyright.com/latest/usage/type-inference Illustrates how Pyright infers the type of a symbol based on the type of the value assigned to it in a single assignment. This includes basic types, empty lists, lists with elements, and list comprehensions. ```python var1 = 3 # Inferred type is int var2 = "hi" # Inferred type is str var3 = list() # Inferred type is list[Unknown] var4 = [3, 4] # Inferred type is list[int] for var5 in [3, 4]: ... # Inferred type is int var6 = [p for p in [1, 2, 3]] # Inferred type is list[int] ``` -------------------------------- ### Report Unreachable Code Safely Source: https://docs.basedpyright.com/latest/benefits-over-pyright/fixes-for-rules This example demonstrates how Basedpyright's `reportUnreachable` rule identifies code that will not be type checked, particularly in common `sys.version_info` checks, which Pyright might overlook. ```python if sys.version_info < (3, 13): 1 + "" # no error ``` -------------------------------- ### Verify Type Completeness with Pyright CLI Source: https://docs.basedpyright.com/latest/usage/typed-libraries Use the `--verifytypes` option with the Pyright CLI to analyze a library for type completeness. Append `--verbose` for more details or `--outputjson` for machine-readable output. Combine with `--ignoreexternal` to focus on your library's code. ```bash pyright --verifytypes ``` ```bash pyright --verifytypes --verbose ``` ```bash pyright --verifytypes --outputjson ``` ```bash pyright --verifytypes --ignoreexternal ``` -------------------------------- ### Run Localization Helper Script Source: https://docs.basedpyright.com/latest/development/localization Execute the localization helper script using either 'uv' or by running an npm script. This tool assists in checking and comparing translation messages. ```bash # use uv ./pw uv run build/py_latest/localization_helper.py ``` ```bash # or from inside the venv npm run localization-helper ``` -------------------------------- ### Write Baseline File with basedpyright CLI Source: https://docs.basedpyright.com/latest/benefits-over-pyright/baseline Run this command in your terminal to generate the initial baseline file. Commit this file to share baselined errors with your team. ```bash basedpyright --writebaseline ``` -------------------------------- ### Constraint Solver: Type Widening (Union vs. Join) Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Illustrates the difference in type widening during constraint solving, where Pyright uses unions and Mypy typically uses joins. ```python T = TypeVar("T") def func(val1: T, val2: T) -> T: ... reveal_type(func("", 1)) # mypy: object, pyright: str | int ``` -------------------------------- ### Pyright Configuration using pyproject.toml Source: https://docs.basedpyright.com/latest/configuration/config-files This TOML file configures Basedpyright settings within the standard pyproject.toml format, under the [tool.basedpyright] section. It mirrors the settings found in pyrightconfig.json for file inclusion/exclusion, constants, Python environments, and diagnostic rules. ```toml [tool.basedpyright] include = ["src"] exclude = ["**\/node_modules", "**\/__pycache__", "src/experimental", "src/typestubs" ] ignore = ["src/oldstuff"] defineConstant = { DEBUG = true } stubPath = "src/stubs" reportMissingImports = "error" reportMissingTypeStubs = false pythonVersion = "3.6" pythonPlatform = "Linux" executionEnvironments = [ { root = "src/web", pythonVersion = "3.5", pythonPlatform = "Windows", extraPaths = [ "src/service_libs" ], reportMissingImports = "warning" }, { root = "src/sdk", pythonVersion = "3.0", extraPaths = [ "src/backend" ] }, { root = "src/tests", reportPrivateUsage = false, extraPaths = ["src/tests/e2e", "src/sdk" ]}, { root = "src" } ] ``` -------------------------------- ### Positional-Only Parameters (Python < 3.8) Source: https://docs.basedpyright.com/latest/usage/typed-libraries For compatibility with Python versions prior to 3.8, name positional-only parameters with an identifier starting with a double underscore (__). ```python def compare_values(__value1: T, __value2: T) -> bool: ... ``` -------------------------------- ### Configure Baseline File Path Source: https://docs.basedpyright.com/latest/benefits-over-pyright/baseline Customize the location of the baseline file using the 'baselineFile' setting in your configuration or via the CLI argument. ```json { "basedpyright": { "baselineFile": "./my-custom-baseline.json" } } ``` -------------------------------- ### Override Specific Settings with Strict Mode Source: https://docs.basedpyright.com/latest/configuration/comments Combine 'strict' mode with specific diagnostic rule overrides. This example enables strict checking but disables 'reportPrivateUsage'. ```python # pyright: strict, reportPrivateUsage=false ``` -------------------------------- ### Enable BasedPyright LSP in Neovim (0.11+) Source: https://docs.basedpyright.com/latest/installation/ides For Neovim versions 0.11 and above, use this command to enable the BasedPyright language server. ```lua vim.lsp.enable("basedpyright") ``` -------------------------------- ### Local Import in __init__.py Source: https://docs.basedpyright.com/latest/usage/import-statements Explains how `from . import a` in an __init__.py file assigns a reference to submodule `a` to a local variable `a`. ```python from . import a ``` -------------------------------- ### Class and Instance Variables in Python Source: https://docs.basedpyright.com/latest/usage/type-concepts-advanced Demonstrates how class variables can be accessed and modified at both the class and instance levels, and how instance variables can shadow class variables. ```python class A: my_var = 0 def my_method(self): self.my_var = "hi!" a = A() print(A.my_var) # Class variable value of 0 print(a.my_var) # Class variable value of 0 A.my_var = 1 print(A.my_var) # Updated class variable value of 1 print(a.my_var) # Updated class variable value of 1 a.my_method() # Writes to the instance variable my_var print(A.my_var) # Class variable value of 1 print(a.my_var) # Instance variable value of "hi!" A.my_var = 2 print(A.my_var) # Updated class variable value of 2 print(a.my_var) # Instance variable value of "hi!" ``` -------------------------------- ### Basic Command-Line Usage Source: https://docs.basedpyright.com/latest/configuration/command-line The basic command-line usage of basedpyright. Specify options and files to analyze. ```bash basedpyright [options] [files...] ``` -------------------------------- ### Run npm Tasks from Command Line Source: https://docs.basedpyright.com/latest/development/contributing If not using VSCode, npm tasks can be executed from the command line. View available scripts in the root package.json. ```bash npm run script-name ``` -------------------------------- ### Configure PyCharm for basedpyright (Community/Professional) Source: https://docs.basedpyright.com/latest/installation/ides Configure PyCharm to use basedpyright by specifying the language server executable and setting the running mode. This ensures PyCharm uses basedpyright for code analysis. ```text basedpyright-langserver ``` -------------------------------- ### Launch LSP Inspector Source: https://docs.basedpyright.com/latest/development/contributing Task to launch the LSP inspector, allowing browsing of messages between the VSCode extension client and server. Note: This does not work on Windows. ```bash npm: lsp-inspect ``` -------------------------------- ### Import with Alias Source: https://docs.basedpyright.com/latest/usage/import-statements Demonstrates an import statement with an alias. Pyright does not model side effects from such imports. ```python from a.b import Foo as Bar ``` -------------------------------- ### Pyright Configuration using pyrightconfig.json Source: https://docs.basedpyright.com/latest/configuration/config-files This JSON file configures Basedpyright settings, including file inclusion/exclusion, defined constants, stub paths, and diagnostic reporting levels for different Python environments. ```json { "include": [ "src" ], "exclude": [ "**/node_modules", "**/__pycache__", "src/experimental", "src/typestubs" ], "ignore": [ "src/oldstuff" ], "defineConstant": { "DEBUG": true }, "stubPath": "src/stubs", "reportMissingImports": "error", "reportMissingTypeStubs": false, "pythonVersion": "3.6", "pythonPlatform": "Linux", "executionEnvironments": [ { "root": "src/web", "pythonVersion": "3.5", "pythonPlatform": "Windows", "extraPaths": [ "src/service_libs" ], "reportMissingImports": "warning" }, { "root": "src/sdk", "pythonVersion": "3.0", "extraPaths": [ "src/backend" ] }, { "root": "src/tests", "reportPrivateUsage": false, "extraPaths": [ "src/tests/e2e", "src/sdk" ] }, { "root": "src" } ] } ``` -------------------------------- ### Recommend BasedPyright Extension in VSCode Workspace Source: https://docs.basedpyright.com/latest/installation/ides Add this to your `.vscode/extensions.json` to recommend the BasedPyright extension to other developers working on the same project. ```json { "recommendations": ["detachhead.basedpyright"] } ``` -------------------------------- ### Generic List Invariance Example Source: https://docs.basedpyright.com/latest/getting_started/type-concepts Illustrates why list[int] is not assignable to list[int | None]. Appending None to the latter, which refers to the same list object, would violate the type of the former and cause a runtime exception. ```python my_list_1: list[int] = [1, 2, 3] my_list_2: list[int | None] = my_list_1 # Error my_list_2.append(None) for elem in my_list_1: print(elem + 1) # Runtime exception ``` -------------------------------- ### Pyright vs. Mypy: Literal Types in Lists Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Pyright does not retain literal types for inferred container types, while Mypy's behavior is inconsistent. This example shows how literal types are handled differently when inferring list types. ```python def func(one: Literal[1]): reveal_type(one) # Literal[1] reveal_type([one]) # pyright: list[int], mypy: list[Literal[1]] reveal_type(1) # Literal[1] reveal_type([1]) # pyright: list[int], mypy: list[int] ``` -------------------------------- ### Type Narrowing with Assignments and Conditionals Source: https://docs.basedpyright.com/latest/usage/type-concepts-advanced Demonstrates type narrowing through direct assignment and conditional logic within a function. Observe how Pyright infers more specific types for variables as code execution progresses. ```Python val_str: str = "hi" val_int: int = 3 def func(val: float | str | complex, test: bool): reveal_type(val) # int | str | complex val = val_int # Type is narrowed to int reveal_type(val) # int if test: val = val_str # Type is narrowed to str reveal_type(val) # str reveal_type(val) # int | str if isinstance(val, int): reveal_type(val) # int print(val) else: reveal_type(val) # str print(val) ``` -------------------------------- ### Configure Basedpyright Config File Path in VS Code for Monorepos Source: https://docs.basedpyright.com/latest/configuration/language-server-settings Specify the configuration file path for Basedpyright in a monorepo setup using VS Code's settings.json. This directs the language server to the correct configuration directory. ```json { "basedpyright.analysis.configFilePath": "${workspaceFolder}/backend" } ``` -------------------------------- ### Generic List Assignability Error Source: https://docs.basedpyright.com/latest/getting_started/type-concepts This example demonstrates a type error when assigning a list of integers (list[int]) to a variable expecting a list that can contain integers or None (list[int | None]). This is due to invariant type parameters in mutable containers. ```python e: list[int] = [3, 4] f: list[int | None] = e # Error ``` -------------------------------- ### Pyright Reports Uninitialized Variable Source: https://docs.basedpyright.com/latest/benefits-over-pyright/improved-reportUninitializedInstanceVariable Pyright flags instance variables that are declared but not initialized within the class body or the __init__ method. This example shows a case where `self.x` is only initialized in a separate `reset` method, which pyright does not consider a valid initialization path. ```python class A: x: int # error: Instance variable "x" is not initialized in the class body or __init__ method def reset(self): # there's no guarantee this will be called so it doesn't count self.x = 3 ``` -------------------------------- ### Modern Tuple Annotation Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Shows the equivalent modern Python syntax for annotating a tuple, which is supported by both Mypy and Pyright. ```python # Using Python syntax from Python 3.6, this # would be annotated as follows: x: float y: float x, y = (3, 4) ``` -------------------------------- ### Local Import with Attribute in __init__.py Source: https://docs.basedpyright.com/latest/usage/import-statements Details how `from .a import b` in an __init__.py file is treated as two sequential imports, first importing `a` and then `b` from `a`. ```python from .a import b ``` -------------------------------- ### Run LSP Client Task Source: https://docs.basedpyright.com/latest/development/contributing Task to run the LSP inspector's client, useful for debugging the language server without the VSCode extension. For Windows users, use the launch config instead of this npm script. ```bash npm: lsp-client ``` -------------------------------- ### Configure Zed with Basedpyright Language Server Source: https://docs.basedpyright.com/latest/configuration/language-server-settings This JSON configuration sets up Zed to use basedpyright as its Python language server and specifies analysis settings. ```json { "languages": { "Python": { "language_servers": ["basedpyright"] } }, "lsp": { "basedpyright": { "settings": { "python": { "pythonPath": ".venv/bin/python" }, "basedpyright.analysis": { "diagnosticMode": "openFilesOnly" } } } } } ``` -------------------------------- ### Update Baseline File via Editor Task Source: https://docs.basedpyright.com/latest/benefits-over-pyright/baseline Use this editor task to generate or update the baseline file. This is an alternative to using the CLI command. ```json "basedpyright: Write new errors to baseline" ``` -------------------------------- ### Abstract Base Class with Abstract Methods Source: https://docs.basedpyright.com/latest/usage/typed-libraries Define abstract base classes using `abc.ABC` and decorate abstract methods with `@abstractmethod`. Subclasses must override these methods. ```python from abc import ABC, abstractmethod class Hashable(ABC): @property @abstractmethod def hash_value(self) -> int: """Subclasses must override""" raise NotImplementedError() @abstractmethod def print(self) -> str: """Subclasses must override""" raise NotImplementedError() ``` -------------------------------- ### Unsupported Side Effect: Aliased Import and Subsequent Import Source: https://docs.basedpyright.com/latest/usage/import-statements Relying on `a.b` being accessible after `import a.b as foo` and `import a` is fragile and not modeled by Pyright. ```python import a.b as foo ``` ```python import a ``` -------------------------------- ### Configure Zed for basedpyright Source: https://docs.basedpyright.com/latest/installation/ides Configure Zed to use a project-specific version of the basedpyright language server. This is recommended to prevent unexpected updates and ensure consistent behavior across development environments. ```json { "lsp": { "basedpyright": { "binary": { "path": ".venv/bin/basedpyright-langserver", "arguments": ["--stdio"] } } } } ``` -------------------------------- ### Constraint Solver: Ambiguous Solution Scoring Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Demonstrates Pyright's approach to resolving ambiguous type variable solutions by scoring and selecting the simplest type, contrasting with Mypy's error-producing behavior on similar cases. ```python T = TypeVar("T") def make_list(x: T | Iterable[T]) -> list[T]: return list(x) if isinstance(x, Iterable) else [x] def func2(x: list[int], y: list[str] | int): v1 = make_list(x) reveal_type(v1) # pyright: "list[int]" ("list[list[T]]" is also a valid answer) v2 = make_list(y) reveal_type(v2) # pyright: "list[int | str]" ("list[list[str] | int]" is also a valid answer) ``` -------------------------------- ### Basedpyright Detects Initialization via __init__ Call Source: https://docs.basedpyright.com/latest/benefits-over-pyright/improved-reportUninitializedInstanceVariable Basedpyright correctly identifies that `self.x` will be initialized because the `__init__` method calls `self.reset()`, which sets `self.x`. This avoids the false positive reported by pyright. ```python class A: x: int # error in pyright, no error in basedpyright def __init__(self) -> None: self.reset() def reset(self): self.x = 3 ``` -------------------------------- ### Enable Basic Type Checking Source: https://docs.basedpyright.com/latest/configuration/comments Use this comment to enable basic type checking, overriding any settings from configuration files or language server settings. ```python # pyright: basic ``` -------------------------------- ### Implicit Module Loads Source: https://docs.basedpyright.com/latest/usage/import-statements Shows how multi-part module names without aliases are treated as sequential imports. This allows access to all modules in the path. ```python import a.b.c ``` -------------------------------- ### Conditional Stub Generation with Docify Source: https://docs.basedpyright.com/latest/benefits-over-pyright/pylance-features Use the `docify` module with the `--if-needed` argument to generate docstrings for stubs only if they are missing for the current platform and Python version, replicating Basedpyright's typeshed generation. ```python python -m docify path/to/typeshed/stdlib --if-needed --in-place ``` -------------------------------- ### Pyright: Literal Math Operations Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Pyright supports 'literal math', enabling precise type inference for simple arithmetic and string concatenation operations involving literals. ```python def func1(a: Literal[1, 2], b: Literal[2, 3]): c = a + b reveal_type(c) # Literal[3, 4, 5] def func2(): c = "hi" + " there" reveal_type(c) # Literal['hi there'] ``` -------------------------------- ### Overload Resolution with Any Argument Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Demonstrates a difference in overload resolution when an Any type is used as an argument. Pyright attempts to preserve type information by returning a supertype, while Mypy returns Any. ```python from typing import overload, Any @overload def func1(x: int) -> int: ... @overload def func1(x: str) -> float: ... def func2(val: Any): reveal_type(func1(val)) # mypy: Any, pyright: float ``` -------------------------------- ### Constraint Solver: Literal Type Handling Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Compares how Pyright and Mypy handle literal types during constraint solving. Pyright retains literals only when necessary, widening them otherwise, while Mypy's behavior is inconsistent. ```python T = TypeVar("T") def identity(x: T) -> T: return x def func(one: Literal[1]): reveal_type(one) # Literal[1] v1 = identity(one) reveal_type(v1) # pyright: int, mypy: Literal[1] reveal_type(1) # Literal[1] v2 = identity(1) reveal_type(v2) # pyright: int, mypy: int ``` -------------------------------- ### Constants with Inferred and Explicit Types Source: https://docs.basedpyright.com/latest/usage/typed-libraries Demonstrates defining constants with inferred and explicit types, including Literal and tuple types. ```python # All-caps constant with inferred type COLOR_FORMAT_RGB = "rgb" # All-caps constant with explicit type COLOR_FORMAT_RGB: Literal["rgb"] = "rgb" LATEST_VERSION: tuple[int, int] = (4, 5) # Final variable with inferred type ColorFormatRgb: Final = "rgb" # Final variable with explicit type ColorFormatRgb: Final[Literal["rgb"]] = "rgb" LATEST_VERSION: Final[tuple[int, int]] = (4, 5) ``` -------------------------------- ### Adding Import Suggestions with Basedpyright Source: https://docs.basedpyright.com/latest/benefits-over-pyright/pylance-features Basedpyright provides code actions for import suggestions, enhancing the developer experience by offering quick fixes for missing imports. ```python # Basedpyright's import suggestion code action ``` -------------------------------- ### Configure Emacs for BasedPyright with lsp-pyright Source: https://docs.basedpyright.com/latest/installation/ides If using `lsp-pyright` (any commit after `0c0d72a`), add this setting to your Emacs config to specify the BasedPyright language server command. ```emacs-lisp (setq lsp-pyright-langserver-command "basedpyright") ``` -------------------------------- ### Lambda Parameter Type Inference with Default Arguments Source: https://docs.basedpyright.com/latest/usage/type-inference Demonstrates type inference for lambda parameters that include default arguments, similar to regular function parameters. ```python cb = lambda x="": x reveal_type(cb) # (x: str = "" -> str) ``` -------------------------------- ### Type Comment for Tuple Annotation Source: https://docs.basedpyright.com/latest/usage/mypy-comparison Demonstrates a type comment for annotating a tuple, which is supported by Mypy but rejected by Pyright. Pyright only supports type comments where modern syntax is available. ```python # The following type comment is supported by # mypy but is rejected by pyright. x, y = (3, 4) # type: (float, float) ``` -------------------------------- ### Type Narrowing with isinstance() Source: https://docs.basedpyright.com/latest/usage/type-concepts-advanced Demonstrates type narrowing using `isinstance()` in both positive and negative cases. The `else` block narrows the type to `Foo` when `val` is not `Bar`. ```python class Foo: pass class Bar: pass def func1(val: Foo | Bar): if isinstance(val, Bar): reveal_type(val) # Bar else: reveal_type(val) # Foo ``` -------------------------------- ### Literal Type Declarations Source: https://docs.basedpyright.com/latest/usage/type-inference Shows how to declare literal types for function return values and parameter types, restricting them to specific constant values. ```python # This function is allowed to return only values 1, 2 or 3. def func1() -> Literal[1, 2, 3]: ... # This function must be passed one of three specific string values. def func2(mode: Literal["r", "w", "rw"]) -> None: ... ```