### Build Pyright Extended LSP from Source Source: https://github.com/replit/pyright-extended/blob/main/README.md Steps to build the pyright-langserver from source. This involves installing Node.js and npm dependencies, building the LSP package, and making the language server executable. The final step is to start the LSP server, typically with `--stdio` for communication. ```bash cd ./packages/pyright && npm run build chmod +x ./packages/pyright/langserver.index.js ./packages/pyright/langserver.index.js --stdio ``` -------------------------------- ### Neovim Setup for Pyright Extended LSP Source: https://github.com/replit/pyright-extended/blob/main/README.md Configures Neovim to use pyright-extended as a Language Server Protocol (LSP) client. This Lua script sets up the LSP configuration, including the command to start the language server, filetypes it supports, and root directory detection. It also configures Python-specific analysis settings. ```lua local lspconfig = require 'lspconfig' local configs = require 'lspconfig.configs' local util = require 'lspconfig.util' if not configs["pyright-extended"] then configs["pyright-extended"] = { default_config = { cmd = {'pyright-langserver', '--stdio'}, filetypes = { "python" }, autostart = true, root_dir = util.root_pattern('pyproject.toml'), single_file_support = true, settings = { python = { analysis = { autoSearchPaths = true, useLibraryCodeForTypes = true } } } } } end lspconfig["pyright-extended"].setup{} vim.lsp.set_log_level("INFO") ``` -------------------------------- ### Install Pyright via Python Package Manager Source: https://github.com/replit/pyright-extended/blob/main/docs/installation.md Installs the Pyright command-line tool using pip or conda. This method also handles Node.js installation and updates. The tool can then be executed from the command line with various options. ```shell pip install pyright ``` ```shell conda install pyright ``` ```shell pyright ``` -------------------------------- ### Install All Dependencies for Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/build-debug.md Installs all necessary dependencies for Pyright and its sub-projects. Requires Node.js version 16.x. Executes an npm script in the root directory of the cloned source. ```bash npm run install:all ``` -------------------------------- ### Install Pyright Extended Globally Source: https://github.com/replit/pyright-extended/blob/main/README.md Installs the pyright-extended package globally using npm. This command makes the package's executables available system-wide. No specific inputs or outputs are detailed, but it's a prerequisite for using the tool directly from the command line. ```bash npm i -g @replit/pyright-extended ``` -------------------------------- ### Install Pyright via NPM Package Manager Source: https://github.com/replit/pyright-extended/blob/main/docs/installation.md Installs the Pyright command-line tool globally using npm. This method requires Node.js to be installed separately. It also includes commands for updating the package. Sudo privileges may be necessary on macOS or Linux for global installation. ```shell npm install -g pyright ``` ```shell sudo npm install -g pyright ``` ```shell sudo npm update -g pyright ``` -------------------------------- ### Pyright Command-Line Usage Example Source: https://github.com/replit/pyright-extended/blob/main/docs/command-line.md This snippet demonstrates the basic command-line structure for running Pyright, including specifying options and target files. It highlights how command-line arguments override configuration files. ```bash pyright --createstub "my_module" pyright --project "./pyrightconfig.json" --verifytypes "requests" pyright --outputjson --pythonversion "3.9" "src/main.py" ``` -------------------------------- ### Run Pyright from a Bash CI Script Source: https://github.com/replit/pyright-extended/blob/main/docs/ci-integration.md This bash script automates the installation and execution of Pyright within a CI environment. It checks Node.js version compatibility, determines if sudo is needed for global npm installations, installs or upgrades Pyright, and then runs Pyright in watch mode. The script includes a version comparison function. ```bash #!/bin/bash PATH_TO_PYRIGHT=`which pyright` vercomp () { if [[ $1 == $2 ]] then return 0 fi local IFS=. local i ver1=($1) ver2=($2) # fill empty fields in ver1 with zeros for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)) do ver1[i]=0 done for ((i=0; i<${#ver1[@]}; i++)) do if [[ -z ${ver2[i]} ]] then # fill empty fields in ver2 with zeros ver2[i]=0 fi if ((10#${ver1[i]} > 10#${ver2[i]})) then return 1 fi if ((10#${ver1[i]} < 10#${ver2[i]})) then return 2 fi done return 0 } # Node version check echo "Checking node version..." NODE_VERSION=`node -v | cut -d'v' -f2` MIN_NODE_VERSION="14.21.3" vercomp $MIN_NODE_VERSION $NODE_VERSION # 1 == gt if [[ $? -eq 1 ]]; then echo "Node version ${NODE_VERSION} too old, min expected is ${MIN_NODE_VERSION}, run:" echo " npm -g upgrade node" exit -1 fi # Do we need to sudo? echo "Checking node_modules dir..." NODE_MODULES=`npm -g root` SUDO="sudo" if [ -w "$NODE_MODULES" ]; then SUDO="#nop" fi # If we can't find pyright, install it. echo "Checking pyright exists..." if [ -z "$PATH_TO_PYRIGHT" ]; then echo "...installing pyright" ${SUDO} npm install -g pyright else # already installed, upgrade to make sure it's current # this avoids a sudo on launch if we're already current echo "Checking pyright version..." CURRENT=`pyright --version | cut -d' ' -f2` REMOTE=`npm info pyright version` if [ "$CURRENT" != "$REMOTE" ]; then echo "...new version of pyright found, upgrading." ${SUDO} npm upgrade -g pyright fi fi echo "done." pyright -w ``` -------------------------------- ### Build VSCode Pyright Extended Extension VSIX Source: https://github.com/replit/pyright-extended/blob/main/README.md Generates a `.vsix` file for the VSCode Pyright Extended extension from source. This process requires installing all dependencies, navigating to the VSCode extension's directory, and running the package script. The resulting `.vsix` file can then be installed manually into VSCode. ```bash npm run install:all cd packages/vscode-pyright; npm run package ``` -------------------------------- ### Python: Examples of Known, Ambiguous, and Unknown Types Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md Demonstrates various Python code examples illustrating the concepts of known, ambiguous, and unknown types for variables, type aliases, functions, and decorators. This helps in understanding how type annotations affect type completeness. ```python # Variable with known type (unambiguous because it uses a literal assignment) a = 3 # Variable with ambiguous type a = [3, 4, 5] # Variable with known (declared) type a: list[int] = [3, 4, 5] # Type alias with partially unknown type (because type # arguments are missing for list and dict) DictOrList = list | dict # Type alias with known type DictOrList = list[Any] | dict[str, Any] # Generic type alias with known type _T = TypeVar("_T") DictOrList = list[_T] | dict[str, _T] # Function with known type def func(a: int | None, b: dict[str, float] = {}) -> None: pass # Function with partially unknown type (because type annotations # are missing for input parameters and return type) def func(a, b): pass # Function with partially unknown type (because of missing # type args on dict) def func(a: int, b: dict) -> None: pass # Function with partially unknown type (because return type # annotation is missing) def func(a: int, b: dict[str, float]): pass # Decorator with partially unknown type (because type annotations # are missing for input parameters and return type) def my_decorator(func): return func # Function with partially unknown type (because type is obscured # by untyped decorator) @my_decorator def func(a: int) -> str: pass # Class with known type class MyClass: height: float = 2.0 def __init__(self, name: str, age: int): self.age: int = age @property def name(self) -> str: ... ``` -------------------------------- ### Install Third-Party Type Stubs (pip) Source: https://github.com/replit/pyright-extended/blob/main/packages/pyright-internal/typeshed-fallback/README.md Installs type stubs for third-party Python packages like 'six' and 'requests' from PyPI. These packages comply with PEP 561 and are automatically released. ```bash pip install types-six types-requests ``` -------------------------------- ### Python Multi-Assignment Type Inference Examples Source: https://github.com/replit/pyright-extended/blob/main/docs/type-inference.md Shows how Pyright infers types for variables when they are assigned values from multiple locations, resulting in a union of types. Includes examples with class attributes and conditional assignments. ```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() ``` -------------------------------- ### Configure Pyright with JSON Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Example of a Pyright configuration file using JSON format. It includes settings for file inclusion/exclusion, type checking reports, Python version and platform targeting, and defines multiple execution environments with specific configurations. ```json { "include": [ "src" ], "exclude": [ "**/node_modules", "**/__pycache__", "src/experimental", "src/typestubs" ], "ignore": [ "src/oldstuff" ], "defineConstant": { "DEBUG": true }, "stubPath": "src/stubs", "reportMissingImports": true, "reportMissingTypeStubs": false, "pythonVersion": "3.6", "pythonPlatform": "Linux", "executionEnvironments": [ { "root": "src/web", "pythonVersion": "3.5", "pythonPlatform": "Windows", "extraPaths": [ "src/service_libs" ] }, { "root": "src/sdk", "pythonVersion": "3.0", "extraPaths": [ "src/backend" ] }, { "root": "src/tests", "extraPaths": [ "src/tests/e2e", "src/sdk" ] }, { "root": "src" } ] } ``` -------------------------------- ### Configure Pyright with TOML Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Example of a Pyright configuration file using TOML format, typically found in a pyproject.toml file. It mirrors the JSON configuration with settings for file inclusion/exclusion, type checking reports, Python version and platform targeting, and defines multiple execution environments. ```toml [tool.pyright] include = ["src"] exclude = ["**/node_modules", "**/__pycache__", "src/experimental", "src/typestubs" ] ignore = ["src/oldstuff"] defineConstant = { DEBUG = true } stubPath = "src/stubs" reportMissingImports = true reportMissingTypeStubs = false pythonVersion = "3.6" pythonPlatform = "Linux" executionEnvironments = [ { root = "src/web", pythonVersion = "3.5", pythonPlatform = "Windows", extraPaths = [ "src/service_libs" ] }, { root = "src/sdk", pythonVersion = "3.0", extraPaths = [ "src/backend" ] }, { root = "src/tests", extraPaths = ["src/tests/e2e", "src/sdk" ]}, { root = "src" } ] ``` -------------------------------- ### Python Single-Assignment Type Inference Examples Source: https://github.com/replit/pyright-extended/blob/main/docs/type-inference.md Illustrates how Pyright infers types for variables based on the type of the value assigned in a single assignment statement. Covers basic types, lists, 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] ``` -------------------------------- ### Pyright Command-Line Flags Source: https://github.com/replit/pyright-extended/blob/main/docs/command-line.md This snippet provides examples of using various Pyright command-line flags to configure type checking behavior. It covers options for creating stubs, specifying project configurations, controlling output format, and setting Python environment details. ```bash # Create stub file for 'numpy' pyright --createstub "numpy" # Use a specific project configuration file pyright -p "./pyrightconfig.json" # Output results in JSON format pyright --outputjson # Specify Python version for analysis pyright --pythonversion "3.10" # Analyze for a specific platform pyright --pythonplatform "Windows" # Use a custom typeshed path pyright -t "/path/to/custom/typeshed" # Enable watch mode for continuous analysis pyright -w ``` -------------------------------- ### Python Import Statement Example: from a.b import Foo as Bar Source: https://github.com/replit/pyright-extended/blob/main/docs/import-statements.md Illustrates the runtime steps performed by a Python import statement, including module loading, namespace caching, attribute lookup, and variable assignment. This highlights potential side effects that Pyright aims to avoid relying on. ```python from a.b import Foo as Bar ``` -------------------------------- ### Optional Type Declaration and Assignment Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts.md Demonstrates the Optional type, which is equivalent to a Union type including None. The example shows valid assignments of an integer, a float, and None, as well as an invalid assignment of an empty string. ```python d: Optional[int] = 4 d = b d = None d = "" # Error ``` -------------------------------- ### Run Pyright in GitLab CI for Code Quality Source: https://github.com/replit/pyright-extended/blob/main/docs/ci-integration.md This configuration sets up Pyright to run within a GitLab CI pipeline and generates a code quality report in a format compatible with GitLab. It installs Pyright and a converter tool, runs Pyright to generate a raw JSON report, converts it to the GitLab code quality format, and finally uploads the report as an artifact. ```yaml job_name: before_script: - npm i -g pyright - npm i -g pyright-to-gitlab-ci script: - pyright --outputjson > report_raw.json after_script: - pyright-to-gitlab-ci --src report_raw.json --output report.json --base_path . artifacts: paths: - report.json reports: codequality: report.json ``` -------------------------------- ### Pyright vs. Mypy: Type Comment Support Differences Source: https://github.com/replit/pyright-extended/blob/main/docs/mypy-comparison.md Illustrates how Mypy fully supports type comments for variable annotations, while Pyright has limited support, primarily for locations where modern Python type hint syntax is also applicable. This example shows a type comment rejected by Pyright but accepted by Mypy. ```python # The following type comment is supported by # mypy but is rejected by pyright. x, y = (3, 4) # type: (float, float) # Using Python syntax from Python 3.6, this # would be annotated as follows: x: float y: float x, y = (3, 4) ``` -------------------------------- ### Generate Type Stub via Command Line (Pyright) Source: https://github.com/replit/pyright-extended/blob/main/docs/type-stubs.md This command generates a draft type stub file for a specified Python library. Ensure the library is installed in the Pyright-configured environment. The generated stub will reside in the configured 'stubPath' (defaulting to './typings'). ```bash pyright --createstub [import-name] ``` -------------------------------- ### Pyright: Literal Math for Operations Source: https://github.com/replit/pyright-extended/blob/main/docs/mypy-comparison.md Shows Pyright's support for 'literal math', where operations between literals result in a new literal type. Examples include arithmetic operations between numeric literals and string concatenation. ```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'] ``` -------------------------------- ### Set Diagnostic Levels Per File (Python) Source: https://github.com/replit/pyright-extended/blob/main/docs/comments.md Configures the diagnostic levels for specific Pyright rules within a Python file. This example sets 'reportPrivateUsage' to 'warning' and 'reportOptionalCall' to 'error'. This allows granular control over which diagnostics are reported and at what severity. ```python # pyright: reportPrivateUsage=warning, reportOptionalCall=error ``` -------------------------------- ### Python Class with Known Type Annotations Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md This Python code defines a class with fully specified and known type annotations. This serves as a clear example of how to properly annotate class members and methods for static type checking. ```python class BaseClass2: height: float = 2.0 ``` -------------------------------- ### Call-Site Return Type Inference Example (Python) Source: https://github.com/replit/pyright-extended/blob/main/docs/type-inference.md Demonstrates Pyright's call-site return type inference where the return type of an unannotated function is inferred based on the types of arguments passed during a function call. This inference can be recursive but is limited for performance. ```python def func1(a, b, c): if c: return a elif c > 3: return b else: return None 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) ``` -------------------------------- ### Pure Instance Variables Declared in Class Methods in Python Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts-advanced.md Shows pure instance variables declared within a class method using `self`, which cannot be accessed via a class reference. Includes examples of initialization and assignment. ```python class A: def __init__(self): self.x: int = 0 self.y: int print(A.x) # Error: 'x' is not a class variable a = A() print(a.x) a.x = 1 a.y = 2 print(f"{a.x}, {a.y}") # 1, 2 print(a.z) # Error: 'z' is not an known member ``` -------------------------------- ### Pyright Type Narrowing with isinstance and Truthiness Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts-advanced.md Demonstrates type narrowing using `isinstance` and truthiness checks in Pyright. This showcases how conditional statements can refine the type of a variable, allowing for more specific type hinting and static analysis. The examples show narrowing for union types and types that can be None. ```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 def func2(val: float | None): if val: reveal_type(val) # float else: reveal_type(val) # float | None ``` -------------------------------- ### Type Variable Scoping in Python Functions with Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts-advanced.md Explains how `TypeVar` instances are bound to specific scopes (classes, functions, type aliases) in Python and how Pyright visualizes this binding with the `@` symbol. Shows an example of an unbound `TypeVar`. ```python from typing import TypeVar, Callable S = TypeVar("S") T = TypeVar("T") def func(a: T) -> T: b: T = a # T refers to T@func reveal_type(b) # T@func c: S # Error: S has no bound scope in this context return b ``` ```python # T is bound to func1 because it appears in a parameter type annotation. def func1(a: T) -> Callable[[T], T]: a: T # OK because T is bound to func1 ``` -------------------------------- ### Report Private Usage Diagnostics in Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Enables or disables diagnostics for the incorrect usage of private or protected variables and functions. Private members are denoted by double underscores, while protected members start with a single underscore. This setting helps enforce encapsulation rules. ```json { "reportPrivateUsage": true } ``` -------------------------------- ### Assignment-based Type Narrowing: Pyright vs. Mypy Source: https://github.com/replit/pyright-extended/blob/main/docs/mypy-comparison.md Explains how Pyright applies type narrowing to variable assignments regardless of annotations, while Mypy skips this narrowing if the target variable has a type annotation. The example shows how Pyright correctly narrows `v2` to `list[int]`, whereas Mypy retains the broader `Sequence[int]` annotation. ```python v1: Sequence[int] v1 = [1, 2, 3] reveal_type(v1) # mypy and pyright both reveal `list[int]` v2: Sequence[int] = [1, 2, 3] reveal_type(v2) # mypy reveals `Sequence[int]` rather than `list[int]` ``` -------------------------------- ### Python Class and Instance Variable Example Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts-advanced.md This Python code snippet demonstrates the difference between class variables and instance variables. It shows how modifying a class variable affects all instances, while assigning to an instance variable only affects that specific instance. Pyright differentiates these types of variables for more precise type checking. ```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!" ``` -------------------------------- ### Run Pyright Tests Source: https://github.com/replit/pyright-extended/blob/main/docs/build-debug.md Executes the test suite for Pyright. Navigate to the 'packages/pyright-internal' directory and run the npm test script. ```bash cd packages/pyright-internal npm run test ``` -------------------------------- ### Build Pyright CLI Source: https://github.com/replit/pyright-extended/blob/main/docs/build-debug.md Builds the Pyright command-line interface. This involves navigating to the 'packages/pyright' directory and executing an npm build script. ```bash cd packages/pyright npm run build ``` -------------------------------- ### Package VS Code Extension for Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/build-debug.md Packages the Pyright VS Code extension into a .vsix file. This requires changing the directory to 'packages/vscode-pyright' and running an npm package script. ```bash cd packages/vscode-pyright npm run package ``` -------------------------------- ### Run Pyright CLI Source: https://github.com/replit/pyright-extended/blob/main/docs/build-debug.md Executes the built Pyright command-line tool. This command is run after the CLI has been successfully built. ```bash node index.js ``` -------------------------------- ### Debug Pyright CLI in VS Code Source: https://github.com/replit/pyright-extended/blob/main/docs/build-debug.md Launches the Pyright command-line tool within the VS Code debugger. Assumes the root source directory is open in VS Code. Offers a faster build/debug loop using a watch task. ```bash # Launch debugger # Press F5 or click the green 'run' icon in the debug sub-panel, selecting 'Pyright CLI'. # Faster loop option (after building pyright-internal with tsc: watch): # Select 'Pyright CLI (pyright-internal)' from the debug target menu and press F5. ``` -------------------------------- ### Debug Pyright VS Code Extension in VS Code Source: https://github.com/replit/pyright-extended/blob/main/docs/build-debug.md Enables debugging of the Pyright VS Code extension. This involves launching a separate VS Code instance with the extension, attaching the debugger, and optionally using watch mode for incremental builds. ```bash # Standard Debugging: # 1. Select 'Pyright extension' from the debug target menu and press F5. # 2. In the new VS Code window, open a Python file. # 3. In the first VS Code window, select 'Pyright extension attach server' and press F5. # Debugging in Watch Mode: # 1. Perform the above steps, but select 'Pyright extension (watch mode)' first. # 2. Changes to Pyright's source will trigger incremental builds and can be reloaded in the second VS Code window. ``` -------------------------------- ### Update and Publish Pyright Extended Source: https://github.com/replit/pyright-extended/blob/main/README.md Commands to update the pyright-extended project from its upstream repository, build the LSP, and publish it to NPM. This process requires appropriate NPM permissions for publishing. It involves pulling the latest changes, rebuilding the LSP, and then executing the publish script. ```bash git pull upstream main npm run build:lsp npm run publish:lsp ``` -------------------------------- ### Add Pyright Badge to README.md Source: https://github.com/replit/pyright-extended/blob/main/docs/ci-integration.md This snippet shows how to add a 'pyright: checked' SVG badge to your project's README.md file. This badge visually indicates that the project has been checked with Pyright. No specific dependencies are required beyond the ability to render SVG images in Markdown. ```text [![Checked with pyright](https://microsoft.github.io/pyright/img/pyright_badge.svg)](https://microsoft.github.io/pyright/) ``` -------------------------------- ### Enable Verbose Logging in Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/import-resolution.md Enables detailed logging for debugging import resolution issues. This can be done via a command-line argument or a configuration file setting. The output appears in the VS Code Output tab when using the Pyright extension. ```bash pyright --verbose ``` ```json { "verboseOutput": true } ``` -------------------------------- ### Verify Type Completeness with Pyright CLI Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md This command-line interface (CLI) command initiates Pyright's type completeness verification for a specified library. It analyzes the library's interface and reports on symbols with ambiguous or unknown types, along with a type completeness score. The `--verbose` option provides more detailed output. ```bash pyright --verifytypes ``` ```bash pyright --verifytypes --verbose ``` -------------------------------- ### Run Pyright as a GitHub Action Source: https://github.com/replit/pyright-extended/blob/main/docs/ci-integration.md This configuration allows you to run Pyright as a GitHub Action. It utilizes the 'jakebailey/pyright-action' to perform type checking on your Python code within the GitHub Actions workflow. You can optionally specify a version of Pyright to use. ```yaml - uses: jakebailey/pyright-action@v1 with: version: 1.1.xxx # Optional (if you want to pin the version) ``` -------------------------------- ### Python List Type Invariance Example Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts.md Demonstrates a type error when assigning a list of integers to a variable expecting a list that can contain integers or None, due to the invariant nature of mutable list types. This highlights how modifying the list can break type assumptions. ```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 ``` -------------------------------- ### Generic Type Assignment (Error Example) Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts.md Highlights a common pitfall with generic types, specifically lists. Assigning a list of integers to a variable declared as a list of optional integers (`list[int | None]`) results in an error, illustrating that type arguments for generic types are not always covariant. ```python e: list[int] = [3, 4] f: list[int | None] = e # Error ``` -------------------------------- ### Override Specific Settings with Strict Mode (Python) Source: https://github.com/replit/pyright-extended/blob/main/docs/comments.md Allows overriding specific Pyright configuration settings while maintaining strict type checking for a Python file. This example enables strict checking but disables the 'reportPrivateUsage' diagnostic. It's useful for fine-tuning type checking rules on a per-file basis. ```python # pyright: strict, reportPrivateUsage=false ``` -------------------------------- ### Pyright Execution Environment Configuration Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Defines configurations for specific execution environments within a Pyright project, allowing for different import paths, Python versions, and target platforms. This is useful for projects with diverse subtrees. ```json { "root": "string", "extraPaths": ["string"], "pythonVersion": "string", "pythonPlatform": "string" } ``` -------------------------------- ### Pyright vs. Mypy: Constraint Solver Type Widening Source: https://github.com/replit/pyright-extended/blob/main/docs/mypy-comparison.md Illustrates the difference in type widening strategies between Pyright and Mypy during constraint solving. Pyright consistently uses unions for widening, whereas Mypy often uses joins. ```python from typing import TypeVar T = TypeVar("T") def func(val1: T, val2: T) -> T: ... reveal_type(func("", 1)) # mypy: object, pyright: str | int ``` -------------------------------- ### Pyright Type Verification with JSON Output Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md This command enables Pyright's type completeness verification and outputs the results in JSON format, making it suitable for consumption by other tools or automated systems. It's useful for integrating type checking into CI/CD pipelines. ```bash pyright --verifytypes --outputjson ``` -------------------------------- ### Pyright: Configure Virtual Environment Paths Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md These settings help Pyright locate and use specific Python virtual environments for import resolution. `venvPath` points to a directory containing virtual environments, and `venv` specifies which environment within that directory to use. This is crucial for accurate type checking in projects with multiple environments. ```json { "venvPath": ".venv", "venv": "myenv" } ``` -------------------------------- ### Literal Type Inference Limitation Example (Python) Source: https://github.com/replit/pyright-extended/blob/main/docs/type-inference.md Illustrates Pyright's behavior regarding literal type inference. Pyright generally avoids inferring literal types for collections like lists to prevent overly restrictive type checking, opting for broader types like `list[int]` instead of `list[Literal[4]]`. ```python # If Pyright inferred the type of var1 to be list[Literal[4]], # any attempt to append a value other than 4 to this list would # generate an error. Pyright therefore infers the broader # type list[int]. var1 = [4] ``` -------------------------------- ### Pyright Extended JSON Output Structure Source: https://github.com/replit/pyright-extended/blob/main/docs/command-line.md This JSON structure represents the overall output when the --outputjson option is used with Pyright Extended. It includes version, timestamp, general diagnostics, and a summary of the analysis. ```javascript { version: string, time: string, generalDiagnostics: Diagnostic[], summary: { filesAnalyzed: number, errorCount: number, warningCount: number, informationCount: number, timeInSec: number } } ``` -------------------------------- ### Pyright: Enable Verbose Output Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md The `verboseOutput` option controls the level of detail in Pyright's logs. Setting it to `true` provides more information, which is particularly helpful when diagnosing complex issues such as import resolution problems. ```json { "verboseOutput": true } ``` -------------------------------- ### Pyright: Specify Include and Exclude Paths Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Control which files and directories Pyright analyzes using `include` and `exclude` options. Wildcards like `**`, `*`, and `?` are supported for flexible path matching. `exclude` paths override `include` paths, allowing you to omit specific directories or files from analysis. ```json { "include": [ "src", "tests/**/*.py" ], "exclude": [ "**/node_modules", "build/" ] } ``` -------------------------------- ### Type Narrowing with Assignments and Type Guards in Python Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts-advanced.md Demonstrates type narrowing in Pyright using Python. It shows how variable types are narrowed based on assignments and conditional checks like isinstance. This helps in understanding how Pyright infers more specific types during code execution flow. ```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) ``` -------------------------------- ### Importing _typeshed Types in Python Implementation Files Source: https://github.com/replit/pyright-extended/blob/main/packages/pyright-internal/typeshed-fallback/stdlib/_typeshed/README.md Demonstrates how to import types from the `_typeshed` package within Python implementation (`.py`) files using `TYPE_CHECKING`. This ensures the types are only available during static analysis and not at runtime. ```python from typing import TYPE_CHECKING if TYPE_CHECKING: from _typeshed import ... ``` -------------------------------- ### Report Missing Super Call Diagnostics in Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Checks if `__init__`, `__init_subclass__`, `__enter__`, or `__exit__` methods in subclasses correctly call their corresponding base class methods. This is crucial for proper initialization and resource management. The default is 'none'. ```json { "reportMissingSuperCall": true } ``` -------------------------------- ### Report Inconsistent Constructor Diagnostics in Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Detects inconsistencies between the signatures of `__init__` and `__new__` methods within a class. This helps maintain predictable object instantiation. The default is 'none'. ```json { "reportInconsistentConstructor": true } ``` -------------------------------- ### Python Keyword-Only Parameters Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md Demonstrates how to define a function with keyword-only parameters using the '*' separator. This ensures that 'dob' must be passed by name. ```python def create_user(age: int, *, dob: date | None = None): ... ``` -------------------------------- ### Python Positional-Only Parameters Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md Illustrates defining functions with positional-only parameters using the '/' separator. It also shows an alternative for older Python versions using double underscores. ```python def compare_values(value1: T, value2: T, /) -> bool: ... def compare_values(__value1: T, __value2: T) -> bool: ... ``` -------------------------------- ### Pyright vs. Mypy: Unions vs. Joins in Type Merging Source: https://github.com/replit/pyright-extended/blob/main/docs/mypy-comparison.md Demonstrates how Pyright uses unions for type merging, preserving type information, while Mypy often uses 'join' operations, which can discard information and lead to false positives. The code shows type reveals in different scenarios to illustrate the differing behaviors. ```python def func1(val: object): if isinstance(val, str): pass elif isinstance(val, int): pass else: return reveal_type(val) # mypy: object, pyright: str | int def func2(condition: bool, val1: str, val2: int): x = val1 if condition else val2 reveal_type(x) # mypy: object, pyright: str | int y = val1 or val2 # In this case, mypy uses a union instead of a join reveal_type(y) # mypy: str | int, pyright: str | int ``` -------------------------------- ### Python Abstract Base Classes and Methods Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md Illustrates how to define abstract base classes (ABCs) and abstract methods using Python's `abc` module. Subclasses must override the abstract 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() ``` -------------------------------- ### Configure Analysis of Unannotated Functions in Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Enables the analysis and reporting of errors for functions and methods that lack type annotations for their parameters or return types. This setting encourages better type hinting practices. Defaults to true. ```python { "analyzeUnannotatedFunctions": true } ``` -------------------------------- ### Empty List Type Inference Based on Context Source: https://github.com/replit/pyright-extended/blob/main/docs/type-inference.md Illustrates how Pyright infers the type of a list variable even when initialized as empty in one code path, by considering a non-empty initialization in another path. This helps in suppressing 'partially unknown type' errors. ```python if some_condition: my_list = [] else: my_list = ["a", "b"] reveal_type(my_list) # list[str] ``` -------------------------------- ### Pyright Exit Codes Explanation Source: https://github.com/replit/pyright-extended/blob/main/docs/command-line.md This snippet illustrates the meaning of Pyright's exit codes. These codes are crucial for scripting and CI/CD pipelines to determine the success or failure of a type-checking process. ```bash # Successful run with no errors (Exit Code 0) # ... pyright command execution ... if [ $? -eq 0 ]; then echo "Pyright: No errors reported." fi # Run with errors reported (Exit Code 1) # ... pyright command execution ... if [ $? -eq 1 ]; then echo "Pyright: Errors were reported." fi # Fatal error during execution (Exit Code 2) # ... pyright command execution ... if [ $? -eq 2 ]; then echo "Pyright: A fatal error occurred." fi # Configuration file error (Exit Code 3) # ... pyright command execution ... if [ $? -eq 3 ]; then echo "Pyright: Configuration file could not be read or parsed." fi # Illegal command-line parameters (Exit Code 4) # ... pyright command execution ... if [ $? -eq 4 ]; then echo "Pyright: Illegal command-line parameters specified." fi ``` -------------------------------- ### Pyright: Set Custom Type Stub Paths Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Configure Pyright to use custom type stubs with `typeshedPath` and `stubPath`. `typeshedPath` points to a directory containing typeshed stubs, useful for contributing to typeshed. `stubPath` points to a directory for your project's custom type stub files, defaulting to './typings'. ```json { "typeshedPath": "/path/to/my/typeshed", "stubPath": "./my_stubs" } ``` -------------------------------- ### NoReturn Type Inference for Functions Without Return Paths Source: https://github.com/replit/pyright-extended/blob/main/docs/type-inference.md Demonstrates Pyright's inference of the `NoReturn` type for functions where all code paths raise an exception. It also covers the exception for abstract methods decorated with `@abstractmethod`. ```python class Foo: # The inferred return type is NoReturn. def method1(self): raise Exception() # The inferred return type is Unknown. @abstractmethod def method2(self): raise NotImplementedError() ``` -------------------------------- ### Pyright vs. Mypy: Constraint Solver with Literals Source: https://github.com/replit/pyright-extended/blob/main/docs/mypy-comparison.md Demonstrates how Pyright and Mypy handle literal types during constraint solving when calling generic functions. Pyright tends to widen literals to non-literal types unless constrained, while Mypy may preserve them. ```python from typing import TypeVar, Literal 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 ``` -------------------------------- ### Enable Experimental Features in Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Enables a set of experimental features that may not be fully documented and are subject to change or removal. These features correspond to proposed or exploratory changes in the Python typing standard and are intended for experimentation. Defaults to false. ```python { "enableExperimentalFeatures": true } ``` -------------------------------- ### Pyright: Add Extra Search Paths Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md The `extraPaths` option specifies additional directories that Pyright should search when resolving imported modules. This is useful for projects with non-standard module structures or when working with external libraries not in the standard Python path. ```json { "extraPaths": [ "./lib", "/opt/shared_libs" ] } ``` -------------------------------- ### Type Annotation Comments for Older Python Versions (Python) Source: https://github.com/replit/pyright-extended/blob/main/docs/type-concepts-advanced.md Illustrates the use of type annotation comments (`# type: ...`) for specifying variable types in Python versions prior to 3.6. Pyright supports these comments, but their future deprecation is noted, recommending replacement with inline annotations. ```Python offsets = [] # type: list[int] self._target = 3 # type: int | str ``` -------------------------------- ### Pyright: Constraint Solver Ambiguous Solution Scoring Source: https://github.com/replit/pyright-extended/blob/main/docs/mypy-comparison.md Shows how Pyright handles ambiguous solutions in constraint solving by scoring potential types based on complexity, favoring simpler types. Mypy may produce errors in similar scenarios. ```python from typing import TypeVar, Iterable 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) ``` -------------------------------- ### Report Unknown Parameter Type Diagnostics in Pyright Source: https://github.com/replit/pyright-extended/blob/main/docs/configuration.md Flags parameters (both input and return types) for functions or methods where the type is not specified or cannot be determined. This encourages explicit type definitions for better code clarity and maintainability. The default is 'none'. ```json { "reportUnknownParameterType": "none" } ``` -------------------------------- ### Python Type Aliases Source: https://github.com/replit/pyright-extended/blob/main/docs/typed-libraries.md Demonstrates various ways to define type aliases in Python, including simple, generic, recursive, and explicitly defined aliases using PEP 613. ```python # Simple type alias FamilyPet = Cat | Dog | GoldFish # Generic type alias ListOrTuple = list[_T] | tuple[_T, ...] # Recursive type alias TreeNode = LeafNode | list["TreeNode"] # Explicit type alias using PEP 613 syntax StrOrInt: TypeAlias = str | int ```