### Install ruff-ecosystem with uv Source: https://github.com/astral-sh/ruff/blob/main/python/ruff-ecosystem/README.md Install the ruff-ecosystem tool from the Ruff project root using uv. ```shell uv tool install -e ./python/ruff-ecosystem ``` -------------------------------- ### Install Ruff with standalone installer (Windows) Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Download and execute the standalone installer script for Ruff on Windows using PowerShell. ```powershell $ # On Windows. $ powershell -c "irm https://astral.sh/ruff/install.ps1 | iex" ``` -------------------------------- ### Install Ruff with pip Source: https://github.com/astral-sh/ruff/blob/main/README.md Install Ruff using pip. ```shell pip install ruff ``` -------------------------------- ### Install Hyperfine for Benchmarking Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Install the `hyperfine` tool, which is used for benchmarking Rust projects. ```shell cargo install hyperfine ``` -------------------------------- ### String Slicing Examples Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/subscript/string.md Illustrates various string slicing techniques, including start, stop, and step parameters, negative indices, and omitting bounds. Also shows type checking for slices. ```python def _(m: int, n: int, s2: str): s = "abcde" reveal_type(s[0:0]) # revealed: Literal[""] reveal_type(s[0:1]) # revealed: Literal["a"] reveal_type(s[0:2]) # revealed: Literal["ab"] reveal_type(s[0:5]) # revealed: Literal["abcde"] reveal_type(s[0:6]) # revealed: Literal["abcde"] reveal_type(s[1:3]) # revealed: Literal["bc"] reveal_type(s[-3:5]) # revealed: Literal["cde"] reveal_type(s[-4:-2]) # revealed: Literal["bc"] reveal_type(s[-10:10]) # revealed: Literal["abcde"] reveal_type(s[0:]) # revealed: Literal["abcde"] reveal_type(s[2:]) # revealed: Literal["cde"] reveal_type(s[5:]) # revealed: Literal[""] reveal_type(s[:2]) # revealed: Literal["ab"] reveal_type(s[:0]) # revealed: Literal[""] reveal_type(s[:2]) # revealed: Literal["ab"] reveal_type(s[:10]) # revealed: Literal["abcde"] reveal_type(s[:]) # revealed: Literal["abcde"] reveal_type(s[::-1]) # revealed: Literal["edcba"] reveal_type(s[::2]) # revealed: Literal["ace"] reveal_type(s[-2:-5:-1]) # revealed: Literal["dcb"] reveal_type(s[::-2]) # revealed: Literal["eca"] reveal_type(s[-1::-3]) # revealed: Literal["eb"] reveal_type(s[None:2:None]) # revealed: Literal["ab"] reveal_type(s[1:None:1]) # revealed: Literal["bcde"] reveal_type(s[None:None:None]) # revealed: Literal["abcde"] start = 1 stop = None step = 2 reveal_type(s[start:stop:step]) # revealed: Literal["bd"] reveal_type(s[False:True]) # revealed: Literal["a"] reveal_type(s[True:3]) # revealed: Literal["bc"] s[0:4:0] # error: [zero-stepsize-in-slice] s[:4:0] # error: [zero-stepsize-in-slice] s[0::0] # error: [zero-stepsize-in-slice] s[::0] # error: [zero-stepsize-in-slice] substring1 = s[m:n] reveal_type(substring1) # revealed: LiteralString substring2 = s2[0:5] reveal_type(substring2) # revealed: str ``` -------------------------------- ### Install Ruff with standalone installers (Windows) Source: https://github.com/astral-sh/ruff/blob/main/README.md Install Ruff using the standalone installer script for Windows. ```shell # On Windows. powershell -c "irm https://astral.sh/ruff/install.ps1 | iex" ``` -------------------------------- ### Install Ruff with pkgx Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Install Ruff using the pkgx package manager. ```console $ pkgx install ruff ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/astral-sh/ruff/blob/main/crates/ty/CONTRIBUTING.md Installs the prek tool and sets up hooks for automatic validation checks. ```shell uv tool install prek prek install ``` -------------------------------- ### Install Ruff with pipx Source: https://github.com/astral-sh/ruff/blob/main/README.md Install Ruff using pipx. ```shell pipx install ruff ``` -------------------------------- ### Python Code Example After Formatting Source: https://github.com/astral-sh/ruff/blob/main/docs/formatter.md Shows the same Python function as above, but with the docstring code example reformatted according to the configuration. ```python def f(x): """ Something about `f`. And an example: .. code-block:: python ( foo, bar, quux, ) = this_is_a_long_line( lion, hippo, lemur, bear, ) """ pass ``` -------------------------------- ### Install Pyright Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/README.md Install Pyright using npm, ignoring scripts to speed up the process. ```shell npm ci --ignore-scripts ``` -------------------------------- ### Start the ty language server Source: https://github.com/astral-sh/ruff/blob/main/crates/ty/docs/cli.md Use this command to start the 'ty' language server. No specific options are detailed for this basic usage. ```bash ty server ``` -------------------------------- ### Python Code Example Before Formatting Source: https://github.com/astral-sh/ruff/blob/main/docs/formatter.md Illustrates a Python function with a docstring containing a code example that will be reformatted. ```python def f(x): ''' Something about `f`. And an example: .. code-block:: python foo, bar, quux = this_is_a_long_line(lion, hippo, lemur, bear) ''' pass ``` -------------------------------- ### Install Ruff with standalone installers (macOS/Linux) Source: https://github.com/astral-sh/ruff/blob/main/README.md Install Ruff using the standalone installer script for macOS and Linux. ```shell # On macOS and Linux. curl -LsSf https://astral.sh/ruff/install.sh | sh ``` -------------------------------- ### Install uv Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Installs the `uv` package manager. This is a prerequisite for several development and release tasks. ```shell curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install Ruff with uv Source: https://github.com/astral-sh/ruff/blob/main/README.md Install Ruff globally or add it to your project's development dependencies using uv. ```shell # With uv. uv tool install ruff@latest ``` ```shell # Or add Ruff to your project. uv add --dev ruff ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Installs pre-commit hooks using uv to automate validation checks before committing. ```shell uv tool install prek prek install ``` -------------------------------- ### Install Ruff Globally with uv Source: https://github.com/astral-sh/ruff/blob/main/docs/faq.md Install Ruff globally using the uv package manager. This is a recommended method for managing Ruff installations. ```console $ uv tool install ruff@latest ``` -------------------------------- ### Install specific Ruff version with standalone installer (Windows) Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Download and execute the standalone installer script for a specific Ruff version on Windows using PowerShell. ```powershell $ powershell -c "irm https://astral.sh/ruff/0.5.0/install.ps1 | iex" ``` -------------------------------- ### Install Ruff on Alpine Linux Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Install Ruff from the community repositories on Alpine Linux using apk. ```console $ apk add ruff ``` -------------------------------- ### Install Ruff on Arch Linux Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Install Ruff from the official repositories on Arch Linux using pacman. ```console $ pacman -S ruff ``` -------------------------------- ### Install Ruff on openSUSE Tumbleweed Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Install Ruff from the distribution repository on openSUSE Tumbleweed using zypper. ```console $ sudo zypper install python3-ruff ``` -------------------------------- ### Install Insta for snapshot testing Source: https://github.com/astral-sh/ruff/blob/main/crates/ty/CONTRIBUTING.md Installs the cargo-insta tool required for updating snapshot tests. ```shell cargo install cargo-insta ``` -------------------------------- ### Install Ruff with pip Source: https://github.com/astral-sh/ruff/blob/main/docs/faq.md Install Ruff using the standard pip package manager. This is a common alternative if uv is not being used. ```console $ pip install ruff ``` -------------------------------- ### Install Nextest for Running Tests Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Installs Nextest, a recommended tool for running Ruff's test suite, though not strictly necessary. ```shell cargo install cargo-nextest --locked ``` -------------------------------- ### Install Insta for Snapshot Tests Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Installs the Insta tool, which is required for updating snapshot tests in the Ruff project. ```shell cargo install cargo-insta ``` -------------------------------- ### Install Ruff Standalone (Windows) Source: https://github.com/astral-sh/ruff/blob/main/docs/faq.md Install Ruff using the standalone PowerShell script for Windows. This method does not require a Rust toolchain. ```console $ powershell -c "irm https://astral.sh/ruff/install.ps1 | iex" ``` -------------------------------- ### Ignore specific rules for Jupyter Notebooks Source: https://github.com/astral-sh/ruff/blob/main/docs/configuration.md Use the `per-file-ignores` setting to apply specific rule exclusions to Jupyter Notebook files. This example ignores all rules starting with `T20` for `.ipynb` files. ```toml [tool.ruff.lint.per-file-ignores] "*.ipynb" = ["T20"] ``` ```toml [lint.per-file-ignores] "*.ipynb" = ["T20"] ``` -------------------------------- ### Initialize Project with uv Source: https://github.com/astral-sh/ruff/blob/main/docs/tutorial.md Initializes a new Python project with a specified library using uv. Creates a basic project structure. ```console $ uv init --lib numbers ``` -------------------------------- ### Run MkDocs Development Server Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Start the MkDocs development server to view the documentation locally. This command uses `uvx` to manage the execution environment. ```shell uvx --with-requirements docs/requirements.txt -- mkdocs serve -f mkdocs.yml ``` -------------------------------- ### Monorepo environment configuration for editable installs Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/import/workspaces.md Configures a virtual environment to include editable source directories for multiple projects. This setup allows Ruff to resolve imports across separate project boundaries. ```toml [environment] # Setup a venv with editables for aproj/src/ and bproj/src/ python = "/.venv" ``` ```pth aproj/src/ ``` ```pth bproj/src/ ``` -------------------------------- ### Develop WASM and Local Server for Ruff Playground (Shell) Source: https://github.com/astral-sh/ruff/blob/main/crates/ruff_python_formatter/CONTRIBUTING.md Set up and run the development environment for the Ruff playground. This involves installing Node.js dependencies, building the WebAssembly component, and starting the local development server. ```shell cd playground && npm ci --ignore-scripts && npm run dev:wasm && npm run dev ``` -------------------------------- ### Mock Environment with Site-Packages Path Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_test/README.md Demonstrates writing a Python file to the mock environment's site-packages directory, adapting to platform differences. ```toml [environment] python = ".venv" python-version = "3.13" ``` -------------------------------- ### Install npm Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Installs Node Package Manager (`npm`), which may be required for certain development tasks. Use your system's package manager (e.g., Homebrew) if preferred. ```shell brew install npm ``` -------------------------------- ### Configure ruff-action with Custom Parameters Source: https://github.com/astral-sh/ruff/blob/main/docs/integrations.md This example shows how to configure `ruff-action` with specific parameters, such as Ruff version, command-line arguments, and source paths, to customize the linting process. ```yaml - uses: astral-sh/ruff-action@v3 with: version: 0.8.0 args: check --select B src: "./src" ``` -------------------------------- ### Initialize AWS MediaTailor Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the MediaTailor client. Provide the region name and any necessary authentication or configuration details. ```python (service_name: Literal['mediatailor'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Project Structure Source: https://github.com/astral-sh/ruff/blob/main/docs/tutorial.md Displays the default file structure created by `uv init`. ```text numbers ├── README.md ├── pyproject.toml └── src └── numbers ├── __init__.py └── py.typed ``` -------------------------------- ### Install specific Ruff version with standalone installers Source: https://github.com/astral-sh/ruff/blob/main/README.md Install a specific version of Ruff using the standalone installer script. ```shell # For a specific version. curl -LsSf https://astral.sh/ruff/0.15.18/install.sh | sh ``` ```shell powershell -c "irm https://astral.sh/ruff/0.15.18/install.ps1 | iex" ``` -------------------------------- ### Initialize AWS MediaPackage v2 Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the MediaPackage v2 client. Provide the region name and any necessary authentication or configuration details. ```python (service_name: Literal['mediapackagev2'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Ruff Configuration in ruff.toml Source: https://github.com/astral-sh/ruff/blob/main/docs/configuration.md This example shows the equivalent configuration in `ruff.toml`, demonstrating the omission of the `[tool.ruff]` header and `tool.ruff` prefix. ```toml [lint] # 1. Enable flake8-bugbear (`B`) rules, in addition to the defaults. select = ["E4", "E7", "E9", "F", "B"] # 2. Avoid enforcing line-length violations (`E501`) ignore = ["E501"] # 3. Avoid trying to fix flake8-bugbear (`B`) violations. unfixable = ["B"] # 4. Ignore `E402` (import violations) in all `__init__.py` files, and in selected subdirectories. [lint.per-file-ignores] "__init__.py" = ["E402"] "**/{tests,docs,tools}/*" = ["E402"] [format] # 5. Use single quotes in `ruff format`. quote-style = "single" ``` -------------------------------- ### Install specific Ruff version with standalone installer (macOS/Linux) Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Download and execute the standalone installer script for a specific Ruff version on macOS and Linux. ```shell $ # For a specific version. $ curl -LsSf https://astral.sh/ruff/0.5.0/install.sh | sh ``` -------------------------------- ### `__new__` and `__init__` with Incompatible Signatures (Example 2) Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/call/constructor.md Continues the analysis of incompatible `__new__` and `__init__` signatures. This example shows a class where `__new__` requires an argument, but `__init__` does not, leading to specific type errors. ```python class Foo2: def __new__(cls, x) -> "Foo2": return object.__new__(cls) def __init__(self): pass # error: [missing-argument] "No argument provided for required parameter `x` of constructor `Foo2.__new__`" reveal_type(Foo2()) # revealed: Foo2 # error: [too-many-positional-arguments] "Too many positional arguments to `Foo2.__init__`: expected 1, got 2" reveal_type(Foo2(42)) # revealed: Foo2 ``` -------------------------------- ### Writing to Mock Site-Packages Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_test/README.md Example of writing a Python file to the mock environment's site-packages directory using a magic path. ```py X = 1 ``` -------------------------------- ### Initialize AWS MediaStore Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the MediaStore client. Ensure the region name is correctly specified for your AWS environment. ```python (service_name: Literal['mediastore'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Install Specific Ruff Version Standalone (macOS/Linux) Source: https://github.com/astral-sh/ruff/blob/main/docs/faq.md Install a specific version of Ruff using the standalone installer script for macOS and Linux. Replace '0.5.0' with the desired version. ```console $ curl -LsSf https://astral.sh/ruff/0.5.0/install.sh | sh ``` -------------------------------- ### Navigate to benchmark directory Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/README.md Change the current directory to the 'ty' benchmark directory. ```shell cd scripts/ty_benchmark ``` -------------------------------- ### Run Ruff from command line Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Execute Ruff commands for linting and formatting after installation. ```console $ ruff check # Lint all files in the current directory. $ ruff format # Format all files in the current directory. ``` -------------------------------- ### Install Ruff with Conda Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Install Ruff from the conda-forge channel using the Conda package manager. ```console $ conda install -c conda-forge ruff ``` -------------------------------- ### Install Ruff with Homebrew Source: https://github.com/astral-sh/ruff/blob/main/docs/installation.md Install Ruff using the Homebrew package manager on macOS and Linux. ```console $ brew install ruff ``` -------------------------------- ### Configure Project Root Directories Source: https://github.com/astral-sh/ruff/blob/main/crates/ty/docs/configuration.md Specify multiple directories for finding first-party modules. Paths are searched in priority order. If unspecified, Ty attempts to detect common project layouts. ```toml [tool.ty.environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` ```toml [environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` -------------------------------- ### Initialize AWS MediaPackage Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the MediaPackage client. Ensure the region name is correctly specified for your AWS environment. ```python (service_name: Literal['mediapackage'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Initialize AWS Metering Marketplace Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the Metering Marketplace client. Provide the region name and any necessary authentication or configuration details. ```python (service_name: Literal['meteringmarketplace'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Configure Ruff with conform.nvim Source: https://github.com/astral-sh/ruff/blob/main/docs/editors/setup.md Set up Ruff formatters (fix, format, organize_imports) for Python files using the conform.nvim plugin. ```lua require("conform").setup({ formatters_by_ft = { python = { -- To fix auto-fixable lint errors. "ruff_fix", -- To run the Ruff formatter. "ruff_format", -- To organize the imports. "ruff_organize_imports", }, }, }) ``` -------------------------------- ### Install nextest for test execution Source: https://github.com/astral-sh/ruff/blob/main/crates/ty/CONTRIBUTING.md Installs the nextest test runner for improved test suite execution. ```shell cargo install cargo-nextest --locked ``` -------------------------------- ### Non-Simplifiable Union Example Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/type_properties/constraints.md Provides an example of a union that does not simplify due to comparability issues with intermediate types. ```python def _[T]() -> None: # (Sub ≤ T@_ ≤ Super) ∨ (SubSub ≤ T@_ ≤ Base) ConstraintSet.range(SubSub, T, Base) | ConstraintSet.range(Sub, T, Super) ``` -------------------------------- ### Fluent Layout for Method Chains (Preview Style) Source: https://github.com/astral-sh/ruff/blob/main/docs/formatter.md Demonstrates Ruff's preview style for formatting long method chains, breaking lines before the first attribute preceding a call. ```python x = ( df .filter(cond) .agg(func) .merge(other) ) ``` -------------------------------- ### Initialize AWS MediaStore Data Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the MediaStore Data client. Specify the region name and other optional parameters. ```python (service_name: Literal['mediastore-data'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Build ty Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/README.md Build the 'ty' binary in release mode. ```shell cargo build --bin ty --release ``` -------------------------------- ### Configure Custom Markdown Extensions (ruff.toml) Source: https://github.com/astral-sh/ruff/blob/main/docs/formatter.md Example TOML configuration for `ruff.toml` to treat `.mdx` and `.qmd` files as Markdown. ```toml # Treat `.mdx` and `.qmd` files as Markdown extension = {mdx="markdown", qmd="markdown"} ``` -------------------------------- ### get Method with Closed TypedDicts Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/typed_dict.md Demonstrates how the `get` method behaves with closed TypedDicts, accounting for declared items. ```Python from typing_extensions import TypedDict class Closed(TypedDict, closed=True): name: str year: int FunctionalClosed = TypedDict( "FunctionalClosed", {"name": str, "year": int}, closed=True, ) class EmptyClosed(TypedDict, closed=True): ... def _(closed: Closed, functional: FunctionalClosed, empty: EmptyClosed, key: str) -> None: reveal_type(closed.get(key)) # revealed: str | int | None reveal_type(functional.get(key)) # revealed: str | int | None reveal_type(empty.get(key)) # revealed: None ``` -------------------------------- ### Neovim 0.11+ Ruff LSP Configuration (No Dependencies) Source: https://github.com/astral-sh/ruff/blob/main/docs/editors/setup.md Store this configuration in nvim/lsp/ruff.lua or nvim/after/lsp/ruff.lua for Neovim 0.11+ without external dependencies. ```lua ---@type vim.lsp.Config return { cmd = { 'ruff', 'server' }, filetypes = { 'python' }, root_markers = { 'pyproject.toml', 'ruff.toml', '.ruff.toml', '.git' }, init_options = { settings = { -- Ruff language server settings go here } } } ``` -------------------------------- ### Configure Ruff Import Strategy Source: https://github.com/astral-sh/ruff/blob/main/docs/editors/settings.md Set the strategy for loading the Ruff executable. 'fromEnvironment' finds Ruff in the environment, falling back to the bundled version, while 'useBundled' exclusively uses the bundled version. ```json { "ruff.importStrategy": "useBundled" } ``` -------------------------------- ### Example Full Diagnostic Output Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_test/README.md Provides an example of the expected diagnostic output format for a given Python code snippet. ```output mdtest_snippet.py, line 1, col 1: revealed type is 'Literal[1]' ``` -------------------------------- ### TypedDict get() with Gradual Defaults Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/typed_dict.md Explains the type inference for `get()` when a gradual default is provided, resulting in 'Unknown' type. ```python from typing import Any, TypedDict class GradualDefault(TypedDict, total=False): x: int def _(td: GradualDefault, default: Any) -> None: reveal_type(td.get("x", default)) # revealed: Unknown ``` -------------------------------- ### Run benchmarks Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/README.md Execute the 'ty' benchmarks using 'uv run'. Requires hyperfine 1.20 or newer. ```shell uv run benchmark ``` -------------------------------- ### TypedDict get() with Known-Key Context Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/typed_dict.md Demonstrates how `get()` utilizes known-key context for default arguments, especially with nested TypedDicts. ```python from typing import TypedDict class ResolvedData(TypedDict, total=False): x: int class Payload(TypedDict, total=False): resolved: ResolvedData class Payload2(TypedDict, total=False): resolved: ResolvedData def takes_resolved(value: ResolvedData) -> None: ... def _(payload: Payload) -> None: reveal_type(payload.get("resolved", {})) # revealed: ResolvedData takes_resolved(payload.get("resolved", {})) def _(payload: Payload | Payload2) -> None: reveal_type(payload.get("resolved", {})) # revealed: ResolvedData takes_resolved(payload.get("resolved", {})) ``` -------------------------------- ### Initialize AWS MediaPackage VOD Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the MediaPackage VOD client. Specify the region name and other optional parameters. ```python (service_name: Literal['mediapackage-vod'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Mac Profiling with Cargo Instruments Source: https://github.com/astral-sh/ruff/blob/main/CONTRIBUTING.md Profile Ruff benchmarks on macOS using `cargo-instruments`. Install the tool with `cargo install cargo-instruments`. ```shell cargo install cargo-instruments ``` ```shell cargo instruments -t time --bench linter --profile profiling -p ruff_benchmark -- --profile-time=1 ``` -------------------------------- ### Multi-File Test Setup Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_test/README.md Define multiple files for a single test by specifying file paths before the code block. Files are relative to the workspace root, which also serves as an import root. ```python from b import C reveal_type(C) # revealed: Literal[C] ``` ```python class C: pass ``` -------------------------------- ### Unsupported Operator Examples in Ruff Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/binary/custom.md These examples show common unsupported operator errors detected by Ruff when using incompatible types. ```python reveal_type(No() @ Yes()) # revealed: Unknown ``` ```python reveal_type(No() / Yes()) # revealed: Unknown ``` ```python reveal_type(No() % Yes()) # revealed: Unknown ``` ```python reveal_type(No() ** Yes()) # revealed: Unknown ``` ```python reveal_type(No() << Yes()) # revealed: Unknown ``` ```python reveal_type(No() >> Yes()) # revealed: Unknown ``` ```python reveal_type(No() | Yes()) # revealed: Unknown ``` ```python reveal_type(No() ^ Yes()) # revealed: Unknown ``` ```python reveal_type(No() & Yes()) # revealed: Unknown ``` ```python reveal_type(No() // Yes()) # revealed: Unknown ``` -------------------------------- ### Overloaded Function Usage Example Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/annotations/callable.md An example showcasing the usage of an overloaded function `foo` within a loop, processing a range of integers. ```python from typing import overload @overload def foo(x: int) -> str: ... @overload def foo(x: str) -> str: ... def foo(x: int | str) -> str: return str(x) def errors() -> None: for x in map(foo, range(1, 10)): print(x) ``` -------------------------------- ### Enum with Custom Start Value Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/enums.md Shows how to use the 'start' keyword argument to specify the initial value for Enum and Flag members. ```Python from enum import Enum, Flag Color = Enum("Color", "RED GREEN BLUE", start=0) reveal_type(Color.RED.value) # revealed: Literal[0] reveal_type(Color.GREEN.value) # revealed: Literal[1] reveal_type(Color.BLUE.value) # revealed: Literal[2] Perm = Flag("Perm", "READ WRITE EXECUTE", start=3) reveal_type(Perm.READ.value) # revealed: Literal[3] reveal_type(Perm.WRITE.value) # revealed: Literal[4] reveal_type(Perm.EXECUTE.value) # revealed: Literal[8] ``` -------------------------------- ### Initialize AWS MediaConvert Client Source: https://github.com/astral-sh/ruff/blob/main/scripts/ty_benchmark/snapshots/homeassistant_Pyrefly.txt Use this to initialize the MediaConvert client. Specify the region name and other optional parameters as needed. ```python (service_name: Literal['mediaconvert'], region_name: str | None = ..., api_version: str | None = ..., use_ssl: bool | None = ..., verify: bool | str | None = ..., endpoint_url: str | None = ..., aws_access_key_id: str | None = ..., aws_secret_access_key: str | None = ..., aws_session_token: str | None = ..., config: Config | None = ..., aws_account_id: str | None = ...) -> Unknown ``` -------------------------------- ### Migrate ruff-lsp Configuration to Native Server (JSON) Source: https://github.com/astral-sh/ruff/blob/main/docs/editors/migration.md This example shows how to migrate from using `ruff.lint.args` and `ruff.format.args` to specify a custom configuration file in `ruff-lsp` to using the `ruff.configuration` setting in the native Ruff server. This consolidates configuration for both linting and formatting. ```json { "ruff.lint.args": "--config ~/.config/custom_ruff_config.toml", "ruff.format.args": "--config ~/.config/custom_ruff_config.toml" } ``` ```json { "ruff.configuration": "~/.config/custom_ruff_config.toml" } ``` -------------------------------- ### Non-callable __init_subclass__ Example Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/lint_docs/non-callable-init-subclass.md This example shows a class `Super` with `__init_subclass__` set to `None`. Attempting to subclass `Super` will result in a `TypeError` at runtime. ```python class Super: __init_subclass__ = None class Sub(Super): ... ``` -------------------------------- ### Basic Dataclass Fields Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/dataclasses/fields.md Demonstrates defining fields with default values and controlling initialization with `init=False`. Shows how to create instances and assign values to fields. ```Python from dataclasses import dataclass, field @dataclass class Member: name: str role: str = field(default="user") tag: str | None = field(default=None, init=False) # revealed: (self: Member, name: str, role: str = "user") -> None reveal_type(Member.__init__) alice = Member(name="Alice", role="admin") reveal_type(alice.role) # revealed: str alice.role = "moderator" # `tag` is marked as `init=False`, so this is an # error: [unknown-argument] "Argument `tag` does not match any known parameter" bob = Member(name="Bob", tag="VIP") ``` -------------------------------- ### Multiline Interpolated String Suppression (Start Line) Source: https://github.com/astral-sh/ruff/blob/main/crates/ty_python_semantic/resources/mdtest/suppressions/type_ignore.md For multiline interpolated strings, the `type: ignore` comment can be placed on the line where the expression starts. ```python # fmt:off a = f""" { 10 / # type: ignore 0 } """ ```