### Example of Insecure Function Call Source: https://docs.astral.sh/ruff/rules/start-process-with-no-shell This example demonstrates calling `os.spawnlp` without a shell, which can be a security risk if user input is not sanitized. This rule is less severe than starting a process with a shell. ```python import os def insecure_function(arbitrary_user_input: str): os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", arbitrary_user_input) ``` -------------------------------- ### Install Hyperfine Source: https://docs.astral.sh/ruff/contributing Install the hyperfine benchmarking tool using Cargo. ```bash cargo install hyperfine ``` -------------------------------- ### Install npm Source: https://docs.astral.sh/ruff/contributing Install Node Package Manager (npm). Use your system's package manager (e.g., Homebrew) for installation. ```bash brew install npm ``` -------------------------------- ### Install Ruff with pkgx Source: https://docs.astral.sh/ruff/installation Install Ruff using `pkgx` from the `pkgx` registry. This command installs the `ruff` package. ```bash $ pkgx install ruff ``` -------------------------------- ### Install Ruff Standalone (Windows) Source: https://docs.astral.sh/ruff/faq Install Ruff using the standalone installer script for Windows systems. ```powershell $ powershell -c "irm https://astral.sh/ruff/install.ps1 | iex" ``` -------------------------------- ### Install Ruff with pip Source: https://docs.astral.sh/ruff/installation Install Ruff using `pip`, the standard Python package installer. This method installs Ruff globally. ```bash $ # With pip. $ pip install ruff ``` -------------------------------- ### Install cargo-instruments Source: https://docs.astral.sh/ruff/contributing Installs the `cargo-instruments` tool for profiling on macOS. ```bash cargo install cargo-instruments ``` -------------------------------- ### Custom Ruff Configuration Example (pyproject.toml) Source: https://docs.astral.sh/ruff/configuration This example demonstrates how to customize Ruff's linting and formatting rules in pyproject.toml, including enabling specific rule sets, ignoring others, and configuring per-file ignores. ```toml [tool.ruff.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. [tool.ruff.lint.per-file-ignores] "__init__.py" = ["E402"] "**/{tests,docs,tools}/*" = ["E402"] [tool.ruff.format] # 5. Use single quotes in `ruff format`. quote-style = "single" ``` -------------------------------- ### Install Ruff with uv Source: https://docs.astral.sh/ruff/installation Install Ruff using `uv` as a development dependency for your project. This is the recommended approach for managing Ruff within a project. ```bash $ # Install Ruff globally. $ uv tool install ruff@latest $ # Or add Ruff to your project. $ uv add --dev ruff ``` -------------------------------- ### Install uv Source: https://docs.astral.sh/ruff/contributing Install the 'uv' package manager using curl. This is a prerequisite for some development tasks. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install Ruff Standalone (macOS/Linux) Source: https://docs.astral.sh/ruff/faq Install Ruff using the standalone installer script for macOS and Linux systems. ```bash $ curl -LsSf https://astral.sh/ruff/install.sh | sh ``` -------------------------------- ### Install critcmp Source: https://docs.astral.sh/ruff/contributing Installs the `critcmp` tool, used for comparing benchmark recordings. ```bash cargo install critcmp ``` -------------------------------- ### Docstring Code Example After Formatting Source: https://docs.astral.sh/ruff/formatter Shows the same Python function as above, but with the docstring code example reformatted by Ruff to adhere to the configured line length. ```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 ``` -------------------------------- ### Enable and apply unsafe fixes Source: https://docs.astral.sh/ruff/linter Command-line examples for showing and applying unsafe fixes with Ruff. ```shell # Show unsafe fixes ruff check --unsafe-fixes ``` ```shell # Apply unsafe fixes ruff check --fix --unsafe-fixes ``` -------------------------------- ### Install Pre-commit Hooks Source: https://docs.astral.sh/ruff/contributing Installs pre-commit hooks using uv to automatically run validation checks when making a commit. ```bash uv tool install prek prek install ``` -------------------------------- ### Install Ruff with standalone installers Source: https://docs.astral.sh/ruff/installation Install Ruff using standalone shell scripts for macOS and Linux, or PowerShell for Windows. Supports specific versions. ```bash $ # On macOS and Linux. $ curl -LsSf https://astral.sh/ruff/install.sh | sh $ # On Windows. $ powershell -c "irm https://astral.sh/ruff/install.ps1 | iex" $ # For a specific version. $ curl -LsSf https://astral.sh/ruff/0.5.0/install.sh | sh $ powershell -c "irm https://astral.sh/ruff/0.5.0/install.ps1 | iex" ``` -------------------------------- ### Install Ruff with pipx Source: https://docs.astral.sh/ruff/faq Install Ruff in an isolated environment using pipx. ```bash $ pipx install ruff ``` -------------------------------- ### Install Ruff with pipx Source: https://docs.astral.sh/ruff/installation Install Ruff using `pipx`, a tool for installing and running Python applications in isolated environments. This method installs Ruff globally. ```bash $ # With pipx. $ pipx install ruff ``` -------------------------------- ### Install Ruff on Alpine Linux Source: https://docs.astral.sh/ruff/installation Install Ruff on Alpine Linux using `apk` from the testing repositories. This command installs the `ruff` package. ```bash $ apk add ruff ``` -------------------------------- ### Custom Ruff Configuration Example (ruff.toml) Source: https://docs.astral.sh/ruff/configuration This example shows custom Ruff linting configurations in ruff.toml, such as enabling flake8-bugbear rules, ignoring specific violations like line length, and disabling fixes for certain rule sets. ```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"] ``` -------------------------------- ### Sorted __slots__ Example Source: https://docs.astral.sh/ruff/rules/unsorted-dunder-slots This example shows the corrected, naturally sorted __slots__ definition. Ensure consistency in your slot definitions. ```python class Dog: __slots__ = "breed", "name" ``` -------------------------------- ### Install Insta for Snapshot Tests Source: https://docs.astral.sh/ruff/contributing Installs the Insta tool, which is required for updating snapshot tests in Ruff development. ```bash cargo install cargo-insta ``` -------------------------------- ### Install Ruff Globally with uv Source: https://docs.astral.sh/ruff/faq Use this command to install the latest version of Ruff globally using the uv package manager. ```bash $ uv tool install ruff@latest ``` -------------------------------- ### Install Ruff on openSUSE Tumbleweed Source: https://docs.astral.sh/ruff/installation Install Ruff on openSUSE Tumbleweed using `zypper` from the distribution repository. This command installs the `python3-ruff` package. ```bash $ sudo zypper install python3-ruff ``` -------------------------------- ### Generate MkDocs Site Source: https://docs.astral.sh/ruff/contributing Use this command to generate the MkDocs site locally. Ensure the Rust toolchain is installed first. ```bash uv run --no-project --isolated --with-requirements docs/requirements.txt scripts/generate_mkdocs.py ``` -------------------------------- ### Incomplete Google-Style Docstring Example Source: https://docs.astral.sh/ruff/rules/undocumented-param This example shows a function with an incomplete Google-style docstring where the 'time' parameter is not documented in the 'Args' section. This violates the D417 rule. ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ try: return distance / time except ZeroDivisionError as exc: raise FasterThanLightError from exc ``` -------------------------------- ### Initialize Project with uv Source: https://docs.astral.sh/ruff/tutorial Initializes a new Python project using uv. This sets up the basic project structure. ```bash $ uv init --lib numbers ``` -------------------------------- ### Nested If Statement Example Source: https://docs.astral.sh/ruff/rules/collapsible-if This snippet shows a common pattern of nested if statements that can be simplified. It requires no specific setup. ```python if foo: if bar: ... ``` -------------------------------- ### Public __init__ method with docstring Source: https://docs.astral.sh/ruff/rules/undocumented-public-init This example demonstrates the correct way to document a public __init__ method with a docstring, including a brief description. ```python class City: def __init__(self, name: str, population: int) -> None: """Initialize a city with a name and population.""" self.name: str = name self.population: int = population ``` -------------------------------- ### Linux Profiling Setup Source: https://docs.astral.sh/ruff/contributing Prepares the `ruff_benchmark` crate for profiling on Linux by building with the `profiling` profile and then running `perf record`. ```bash cargo bench -p ruff_benchmark --no-run --profile=profiling && perf record --call-graph dwarf -F 9999 cargo bench -p ruff_benchmark --profile=profiling -- --profile-time=1 ``` -------------------------------- ### Docstring with non-capitalized section headers Source: https://docs.astral.sh/ruff/rules/non-capitalized-section-name This example shows a docstring with section headers like 'args', 'returns', and 'raises' that do not start with a capital letter. This violates the D405 rule. ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. args: distance: Distance traveled. time: Time spent traveling. returns: Speed as distance divided by time. raises: FasterThanLightError: If speed is greater than the speed of light. """ try: return distance / time except ZeroDivisionError as exc: raise FasterThanLightError from exc ``` -------------------------------- ### Run Ruff with uvx Source: https://docs.astral.sh/ruff/installation Invoke Ruff directly using `uvx` for linting and formatting. This method does not require a prior installation. ```bash uvx ruff check # Lint all files in the current directory. uvx ruff format # Format all files in the current directory. ``` -------------------------------- ### Run MkDocs Development Server Source: https://docs.astral.sh/ruff/contributing Start the MkDocs development server to preview documentation changes locally. This command should be run after generating the site. ```bash uvx --with-requirements docs/requirements.txt -- mkdocs serve -f mkdocs.yml ``` -------------------------------- ### Incorrect Docstring Style (D404) Source: https://docs.astral.sh/ruff/rules/docstring-starts-with-this This example shows a docstring that violates PEP 257 by starting with 'This'. The rule flags this pattern to encourage imperative mood phrasing. ```python def average(values: list[float]) -> float: """This function returns the mean of the given values.""" ``` -------------------------------- ### Neovim LSP Configuration with nvim-lspconfig (Neovim 0.10 and earlier) Source: https://docs.astral.sh/ruff/editors/setup Setup the Ruff LSP server using the `nvim-lspconfig` plugin, recommended for Neovim 0.10 and earlier. ```lua require('lspconfig').ruff.setup({ init_options = { settings = { -- Ruff language server settings go here } } }) ``` -------------------------------- ### Incorrect super() usage Source: https://docs.astral.sh/ruff/rules/super-without-brackets This example demonstrates the incorrect usage of `super` without parentheses, which will lead to an AttributeError. Ensure `super()` is called with parentheses to get the proxy object. ```python class Animal: @staticmethod def speak(): return "This animal says something." class Dog(Animal): @staticmethod def speak(): original_speak = super.speak() # ERROR: `super.speak()` return f"{original_speak} But as a dog, it barks!" ``` -------------------------------- ### Correct Shebang Placement Source: https://docs.astral.sh/ruff/rules/shebang-not-first-line This example demonstrates the correct placement of a shebang directive at the very beginning of the file. ```python #!/usr/bin/env python3 foo = 1 ``` -------------------------------- ### Fix Mixed Tabs and Spaces (E101) Source: https://docs.astral.sh/ruff/rules/mixed-spaces-and-tabs Use spaces exclusively for indentation to adhere to common Python style guides. This example shows the conversion from mixed tabs and spaces to spaces only. ```python if a == 0: a = 1 b = 1 ``` ```python if a == 0: a = 1 b = 1 ``` -------------------------------- ### isort Import Sorting Example Source: https://docs.astral.sh/ruff/faq Shows how isort splits non-aliased imports into separate statements at each aliased boundary. ```python from numpy import cos, int8, int16, int32, int64 from numpy import sin as np_sin from numpy import tan, uint8, uint16, uint32, uint64 ``` -------------------------------- ### Example of indentation with spaces Source: https://docs.astral.sh/ruff/settings Demonstrates code indented with spaces, the default style. ```python def f(): print("Hello") # Spaces indent the `print` statement. ``` -------------------------------- ### Incorrect Model Field and Meta Order (DJ012) Source: https://docs.astral.sh/ruff/rules/django-unordered-body-content-in-model This example shows a Django Model with the `__str__` method defined before the database fields and `Meta` class, violating the Django Style Guide. This ordering can lead to confusion and is flagged by the DJ012 linter. ```python from django.db import models class StrBeforeFieldModel(models.Model): class Meta: verbose_name = "test" verbose_name_plural = "tests" def __str__(self): return "foobar" first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=40) ``` -------------------------------- ### Correct Model Field and Meta Order (DJ012) Source: https://docs.astral.sh/ruff/rules/django-unordered-body-content-in-model This example demonstrates the correct ordering for a Django Model according to the Django Style Guide. Database fields are listed first, followed by the `Meta` class, and then methods like `__str__`. This adheres to the DJ012 linter's requirements. ```python from django.db import models class StrBeforeFieldModel(models.Model): first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=40) class Meta: verbose_name = "test" verbose_name_plural = "tests" def __str__(self): return "foobar" ``` -------------------------------- ### Example Project Structure for Import Categorization Source: https://docs.astral.sh/ruff/contributing Illustrates a typical project directory structure used to understand Ruff's 'project root' and 'package root' concepts for import analysis. ```text my_project ├── pyproject.toml └── src └── foo ├── __init__.py └── bar ├── __init__.py └── baz.py ``` -------------------------------- ### Configure fixable and unfixable rules in ruff.toml Source: https://docs.astral.sh/ruff/linter Example configuration in ruff.toml to control which Ruff lint rules are fixable. ```toml [lint] fixable = ["ALL"] unfixable = ["F401"] ``` -------------------------------- ### Extend Configuration Source: https://docs.astral.sh/ruff/settings Merge settings from another Ruff configuration file. This example extends a parent `pyproject.toml` and overrides `line-length`. ```toml [tool.ruff] # Extend the `pyproject.toml` file in the parent directory. extend = "../pyproject.toml" # But use a different line length. line-length = 100 ``` ```toml # Extend the `pyproject.toml` file in the parent directory. extend = "../pyproject.toml" # But use a different line length. line-length = 100 ``` -------------------------------- ### Configure Ruff Project Root and Source Directories Source: https://docs.astral.sh/ruff/faq Example of how to configure the project root and source directories in Ruff's configuration files. This is useful when extending configuration files from different directories. ```toml [tool.ruff] extend = "../pyproject.toml" src = ["../src"] ``` ```toml extend = "../pyproject.toml" src = ["../src"] ``` -------------------------------- ### Enable Preview Mode and Select Preview Rules Source: https://docs.astral.sh/ruff/preview Enable preview mode and select preview rules or categories. ```toml [tool.ruff.lint] extend-select = ["HYP"] preview = true ``` ```toml [lint] extend-select = ["HYP"] preview = true ``` ```bash ruff check --extend-select HYP --preview ``` -------------------------------- ### Run Ruff commands Source: https://docs.astral.sh/ruff/installation Execute Ruff commands for linting and formatting after installation. These commands operate on files in the current directory. ```bash $ ruff check # Lint all files in the current directory. $ ruff format # Format all files in the current directory. ``` -------------------------------- ### Use correct sys.version_info comparison Source: https://docs.astral.sh/ruff/rules/bad-version-info-comparison Demonstrates the recommended way to compare sys.version_info using '>='. This ensures accurate version checks and avoids potential bugs. ```python import sys if sys.version_info >= (3, 9): ... ``` -------------------------------- ### Install Ruff with Conda Source: https://docs.astral.sh/ruff/installation Install Ruff using Conda from the `conda-forge` channel. This command installs the `ruff` package. ```bash $ conda install -c conda-forge ruff ``` -------------------------------- ### Configure extend-safe-fixes and extend-unsafe-fixes in ruff.toml Source: https://docs.astral.sh/ruff/linter Example configuration in ruff.toml to adjust the safety of specific Ruff lint rules. ```toml [lint] extend-safe-fixes = ["F601"] extend-unsafe-fixes = ["UP034"] ``` -------------------------------- ### Install Ruff with Homebrew Source: https://docs.astral.sh/ruff/installation Install Ruff using Homebrew for macOS and Linuxbrew users. This command installs the `ruff` package. ```bash $ brew install ruff ``` -------------------------------- ### Correct sys.platform check Source: https://docs.astral.sh/ruff/rules/unrecognized-platform-check This example demonstrates the correct way to check sys.platform using simple string comparisons like '==' or '!='. This ensures compatibility with type checkers. ```python import sys if sys.platform == "linux": # Linux specific definitions ... else: # Posix specific definitions ... ``` -------------------------------- ### Configure Ruff Source Directories and Linting Rules Source: https://docs.astral.sh/ruff/faq This snippet shows how to configure source directories and select specific linting rules, including isort configurations for known first-party modules. ```toml [tool.ruff] src = ["src", "tests"] [tool.ruff.lint] select = [ # Pyflakes "F", # Pycodestyle "E", "W", # isort "I001" ] [tool.ruff.lint.isort] known-first-party = ["my_module1", "my_module2"] ``` ```toml src = ["src", "tests"] [lint] select = [ # Pyflakes "F", # Pycodestyle "E", "W", # isort "I001" ] [lint.isort] known-first-party = ["my_module1", "my_module2"] ``` -------------------------------- ### Install Specific Ruff Version Standalone (Windows) Source: https://docs.astral.sh/ruff/faq Install a specific version of Ruff using the standalone installer script for Windows. ```powershell $ powershell -c "irm https://astral.sh/ruff/0.5.0/install.ps1 | iex" ``` -------------------------------- ### Neovim LSP Configuration (without external dependencies) Source: https://docs.astral.sh/ruff/editors/setup This configuration is for Neovim 0.11+ and does not require external dependencies. Store this in `nvim/lsp/ruff.lua` or `nvim/after/lsp/ruff.lua`. ```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 } } } ``` -------------------------------- ### Install Specific Ruff Version Standalone (macOS/Linux) Source: https://docs.astral.sh/ruff/faq Install a specific version of Ruff using the standalone installer script for macOS and Linux. ```bash $ curl -LsSf https://astral.sh/ruff/0.5.0/install.sh | sh ``` -------------------------------- ### Ruff CLI Help Overview Source: https://docs.astral.sh/ruff/configuration Displays the main help message for the Ruff CLI, listing all available top-level commands and global options. Useful for understanding the scope of Ruff's functionality. ```bash Ruff: An extremely fast Python linter and code formatter. Usage: ruff [OPTIONS] Commands: check Run Ruff on the given files or directories rule Explain a rule (or all rules) config List or describe the available configuration options linter List all supported upstream linters clean Clear any caches in the current directory and any subdirectories format Run the Ruff formatter on the given files or directories server Run the language server analyze Run analysis over Python source code version Display Ruff's version help Print this message or the help of the given subcommand(s) Options: -h, --help Print help (see more with '--help') -V, --version Print version Log levels: -v, --verbose Enable verbose logging -q, --quiet Print diagnostics, but nothing else -s, --silent Disable all logging (but still exit with status code "1" upon detecting diagnostics) Global options: --config Either a path to a TOML configuration file (`pyproject.toml` or `ruff.toml`), or a TOML ` = ` pair (such as you might find in a `ruff.toml` configuration file) overriding a specific configuration option (e.g., `--config "lint.line-length = 100"` or `--config "format.quote-style = 'single'"`). Overrides of individual settings using this option always take precedence over all configuration files, including configuration files that were also specified using `--config` --isolated Ignore all configuration files --color Control when colored output is used [possible values: auto, always, never] For help with a specific command, see: `ruff help `. ``` -------------------------------- ### Install Ruff on Arch Linux Source: https://docs.astral.sh/ruff/installation Install Ruff on Arch Linux using `pacman` from the official repositories. This command installs the `ruff` package. ```bash $ pacman -S ruff ``` -------------------------------- ### Configure Ruff Executable Import Strategy Source: https://docs.astral.sh/ruff/editors/settings Choose the strategy for loading the Ruff executable. 'fromEnvironment' finds Ruff in the environment, falling back to the bundled version. 'useBundled' exclusively uses the version bundled with the extension. ```json { "ruff.importStrategy": "useBundled" } ``` -------------------------------- ### Use Async File Open in Async Function Source: https://docs.astral.sh/ruff/rules/blocking-open-call-in-async-function Shows the correct way to open and read a file asynchronously using `anyio`. Ensure `anyio` is installed and imported. ```python import anyio async def foo(): async with await anyio.open_file("bar.txt") as f: contents = await f.read() ``` -------------------------------- ### Install Local Plugins for Claude Code Source: https://docs.astral.sh/ruff/contributing Install local agent skills for ty development in Claude Code. These skills are automatically discovered by Codex or can be manually installed for Claude Code. ```bash /plugin marketplace add ./.agents /plugin install ty-skills@ruff-agent-skills ``` -------------------------------- ### Run Ruff over Jupyter Notebooks using nbQA Source: https://docs.astral.sh/ruff/faq Demonstrates how to use nbQA to run Ruff over a Jupyter Notebook file, showing example output with detected errors. ```bash $ nbqa ruff Untitled.ipynb Untitled.ipynb:cell_1:2:5: F841 Local variable `x` is assigned to but never used Untitled.ipynb:cell_2:1:1: E402 Module level import not at top of file Untitled.ipynb:cell_2:1:8: F401 `os` imported but unused Found 3 errors. 1 potentially fixable with the `--fix` option. ``` -------------------------------- ### Corrected Syntax Example Source: https://docs.astral.sh/ruff/rules/syntax-error This snippet shows the corrected version of the previous example, with valid syntax. ```python x = 1 ``` -------------------------------- ### Configuring Ruff Formatters with conform.nvim Source: https://docs.astral.sh/ruff/editors/setup Set up Ruff formatters ('ruff_fix', 'ruff_format', 'ruff_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", }, }, }) ``` -------------------------------- ### Use `extra` for logging with named arguments Source: https://docs.astral.sh/ruff/rules/logging-percent-format This example demonstrates the recommended way to log messages with additional context using the `extra` keyword argument. This defers formatting until the log message is actually processed. ```python import logging logging.basicConfig(format="%(user_id)s - %(message)s", level=logging.INFO) user = "Maria" logging.info("Something happened", extra=dict(user_id=user)) ``` -------------------------------- ### Unsorted __slots__ Example Source: https://docs.astral.sh/ruff/rules/unsorted-dunder-slots This example demonstrates an incorrectly ordered __slots__ definition. Use natural sorting for better code readability. ```python class Dog: __slots__ = "name", "breed" ``` -------------------------------- ### Correct str.format Numbering (Manual) Source: https://docs.astral.sh/ruff/rules/string-dot-format-mixing-automatic Demonstrates the correct way to use str.format with manual numbering for all placeholders. This ensures predictable output and avoids runtime errors. ```python "{0}, {1}".format("Hello", "World") ``` -------------------------------- ### Configure Ruff with Configuration File Path (VS Code) Source: https://docs.astral.sh/ruff/editors/settings Specify the path to a ruff.toml or pyproject.toml file for Ruff configuration in VS Code. User home directory and environment variables are expanded. ```json { "ruff.configuration": "~/path/to/ruff.toml" } ``` -------------------------------- ### Corrected __post_init__ using InitVar Source: https://docs.astral.sh/ruff/rules/post-init-default This example shows the correct way to define parameters with default values for dataclasses using InitVar fields. This ensures the defaults are applied to the generated __init__ method. ```python from dataclasses import InitVar, dataclass @dataclass class Foo: bar: InitVar[int] = 1 baz: InitVar[int] = 2 def __post_init__(self, bar: int, baz: int) -> None: print(bar, baz) foo = Foo() # Prints '1 2'. ``` -------------------------------- ### Unsorted Imports Example Source: https://docs.astral.sh/ruff/rules/unsorted-imports This example shows imports that are not sorted according to common conventions. Use the sorted version for better code readability. ```python import pandas import numpy as np ``` ```python import numpy as np import pandas ``` -------------------------------- ### Documented Public Method (NumPy Style) Source: https://docs.astral.sh/ruff/rules/undocumented-public-method This example demonstrates a public method correctly documented using the NumPy docstring format. Ensure docstrings cover behavior, parameters, and exceptions. ```python class Cat(Animal): def greet(self, happy: bool = True): """Print a greeting from the cat. Parameters ---------- happy : bool, optional Whether the cat is happy, is True by default. Raises ------ ValueError If the cat is not happy. """ if happy: print("Meow!") else: raise ValueError("Tried to greet an unhappy cat.") ``` -------------------------------- ### Under-Indented Docstring Example (Python) Source: https://docs.astral.sh/ruff/rules/under-indentation This snippet shows an example of an under-indented docstring that violates PEP 257. Use this to identify incorrect formatting. ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` -------------------------------- ### Example mdtest for E402 rule Source: https://docs.astral.sh/ruff/contributing This example demonstrates a minimal mdtest for the 'module-import-not-at-top-of-file' (E402) rule. It uses '# error' comments to assert rule violations. ```markdown ``` -------------------------------- ### Configure Ruff with Configuration File Path (Neovim) Source: https://docs.astral.sh/ruff/editors/settings Configure Ruff's settings in Neovim by providing the path to a ruff.toml or pyproject.toml file. This method supports expansion of user home directory and environment variables. ```lua vim.lsp.config('ruff', { init_options = { settings = { configuration = "~/path/to/ruff.toml" } } }) ``` -------------------------------- ### Migrate ruff-lsp lint.args to native server lint.select and configuration Source: https://docs.astral.sh/ruff/editors/migration Replace `ruff.lint.args` with `ruff.lint.select` for specifying linter rule sets directly in editor settings. Use the `ruff.configuration` setting for options like `--unsafe-fixes` and to specify unfixable rules within the `lint.unfixable` configuration. ```json { "ruff.lint.args": "--select=E,F --unfixable=F401 --unsafe-fixes" } ``` ```json { "ruff.lint.select": ["E", "F"], "ruff.configuration": { "unsafe-fixes": true, "lint": { "unfixable": ["F401"] } } } ``` -------------------------------- ### Remove Unnecessary Range Start Argument Source: https://docs.astral.sh/ruff/rules/unnecessary-range-start Use `range(x)` instead of `range(0, x)` for conciseness, as 0 is the default start value. ```python range(0, 3) ``` ```python range(3) ``` -------------------------------- ### Install Nextest for Test Suite Source: https://docs.astral.sh/ruff/contributing Installs Nextest, a faster test runner, which can be used as an alternative to `cargo test` for running Ruff's test suite. ```bash cargo install cargo-nextest --locked ``` -------------------------------- ### Python Class __init__ with Return Type Annotation Source: https://docs.astral.sh/ruff/rules/missing-return-type-special-method This example demonstrates the corrected version of the `__init__` method, including the `-> None` return type annotation, which satisfies the ANN204 rule. ```python class Foo: def __init__(self, x: int) -> None: self.x = x ``` -------------------------------- ### Over-indented Docstring Example Source: https://docs.astral.sh/ruff/rules/over-indentation This example shows an over-indented docstring that violates PEP 257. The fix involves aligning the docstring's indentation with the opening quotes. ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` -------------------------------- ### Use arguments for logging with positional formatting Source: https://docs.astral.sh/ruff/rules/logging-percent-format This example shows an alternative recommended method for logging messages by passing values as arguments to the logging method. This also defers string formatting until required. ```python import logging logging.basicConfig(format="%(message)s", level=logging.INFO) user = "Maria" logging.info("%s - Something happened", user) ``` -------------------------------- ### Unmatched Suppression Comment Example (RUF104) Source: https://docs.astral.sh/ruff/rules/unmatched-suppression-comment This example demonstrates an unmatched range suppression comment. Use instead a version with explicit enable comments to limit suppression scope. ```python def foo(): # ruff: disable[E501] # unmatched REALLY_LONG_VALUES = [...] print(REALLY_LONG_VALUES) ``` ```python def foo(): # ruff: disable[E501] REALLY_LONG_VALUES = [...] # ruff: enable[E501] print(REALLY_LONG_VALUES) ``` -------------------------------- ### Undocumented Nested Class Example Source: https://docs.astral.sh/ruff/rules/undocumented-public-nested-class This example shows a public nested class 'Bar' within 'Foo' that is missing a docstring, leading to a linter warning. The 'bar.__doc__' attribute is None. ```python class Foo: """Class Foo.""" class Bar: ... bar = Foo.Bar() bar.__doc__ # None ``` -------------------------------- ### Avoid os.mkdir Source: https://docs.astral.sh/ruff/rules/os-mkdir Use pathlib.Path.mkdir() for a more readable and object-oriented approach to creating directories. This is the recommended alternative to os.mkdir. ```python import os os.mkdir("./directory/") ``` ```python from pathlib import Path Path("./directory/").mkdir() ``` -------------------------------- ### Unsafe fix example: Module not callable Source: https://docs.astral.sh/ruff/rules/unreliable-callable-check This rule's fix is unsafe because `hasattr(operator, "__call__")` can be true while `callable(operator)` is false, for example, with imported modules. ```python import operator assert hasattr(operator, "__call__") assert callable(operator) is False ``` -------------------------------- ### Configure First-Party Sources in ruff.toml Source: https://docs.astral.sh/ruff/faq Define the 'src' directories Ruff should consider for first-party imports in ruff.toml. ```toml # Ruff supports a top-level `src` option in lieu of isort's `src_paths` setting. ``` -------------------------------- ### Runtime Error Example for RUF053 Source: https://docs.astral.sh/ruff/rules/class-with-mixed-type-vars This code demonstrates the runtime TypeError that occurs when a class uses PEP 695 type parameters and inherits from Generic. This is an example of the problem RUF053 detects. ```python from typing import Generic, TypeVar U = TypeVar("U") # TypeError: Cannot inherit from Generic[...] multiple times. class C[T](Generic[U]): ... ``` -------------------------------- ### Enable Docstring Code Formatting with Fixed Line Length Source: https://docs.astral.sh/ruff/formatter Configure Ruff to format Python code examples within docstrings and set a fixed line length limit of 20 characters for these examples. ```toml [tool.ruff.format] docstring-code-format = true docstring-code-line-length = 20 ``` ```toml [format] docstring-code-format = true docstring-code-line-length = 20 ``` -------------------------------- ### Enable Preview Mode for Formatting Source: https://docs.astral.sh/ruff/preview Enable preview mode for formatting styles in pyproject.toml, ruff.toml, or via the CLI. ```toml [tool.ruff.format] preview = true ``` ```toml [format] preview = true ``` ```bash ruff format --preview ``` -------------------------------- ### Missing Trailing Comma Example Source: https://docs.astral.sh/ruff/rules/missing-trailing-comma This example shows a dictionary literal without a trailing comma, which violates the COM812 rule. Use trailing commas to reduce diff sizes when adding or removing elements. ```python foo = { "bar": 1, "baz": 2 } ``` ```python foo = { "bar": 1, "baz": 2, } ``` -------------------------------- ### Show Ruff Settings for a File Source: https://docs.astral.sh/ruff/faq Run this command to view the resolved settings Ruff is using for a specific Python file. ```bash ruff check /path/to/code.py --show-settings ``` -------------------------------- ### Select All Rules Source: https://docs.astral.sh/ruff/preview Select all available rules, including preview rules if preview mode is enabled. ```toml [tool.ruff.lint] select = ["ALL"] ``` ```toml [lint] select = ["ALL"] ``` ```bash ruff check --select ALL ``` -------------------------------- ### Implicit Block-level Ignore Range Source: https://docs.astral.sh/ruff/linter If no matching 'enable' comment is found, Ruff treats the range as implicit. The suppression starts at the 'disable' comment and continues until a logical scope indented less than the starting comment is reached. ```python def foo(): # ruff: disable[E741, F841] i = 1 if True: O = 1 l = 1 ``` -------------------------------- ### Blank Lines at Block Start Source: https://docs.astral.sh/ruff/formatter/black Black 24+ allows blank lines at the start of a code block. Ruff consistently removes them to prevent unintentional blank lines, though this behavior may be reconsidered in the future. ```python # Black if x: a = 123 # Ruff if x: a = 123 ``` -------------------------------- ### Enabling Ruff LSP Server in Neovim Source: https://docs.astral.sh/ruff/editors/setup Enable the Ruff LSP server by including this in your `init.lua` after configuring the server. ```lua vim.lsp.enable('ruff') ``` -------------------------------- ### Example of stdlib-module-shadowing violation Source: https://docs.astral.sh/ruff/rules/stdlib-module-shadowing This example demonstrates how creating a local file named 'random.py' and attempting to import from the standard 'random' module results in an ImportError. The error message suggests renaming the local file to avoid conflict. ```bash $ touch random.py $ python3 -c 'from random import choice' Traceback (most recent call last): File "", line 1, in from random import choice ImportError: cannot import name 'choice' from 'random' (consider renaming '/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module) ``` -------------------------------- ### Demonstrate sys.version_info comparison behavior Source: https://docs.astral.sh/ruff/rules/bad-version-info-comparison Illustrates the unexpected results when comparing sys.version_info with operators like '>', '==', and '<='. This behavior is due to how version tuples are compared. ```python >>> import sys >>> print(sys.version_info) sys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0) >>> print(sys.version_info > (3, 8)) True >>> print(sys.version_info == (3, 8)) False >>> print(sys.version_info <= (3, 8)) False >>> print(sys.version_info in (3, 8)) False ```