astral-sh/ruff · error

The `--range` option is only supported when formatting a sin

Error message

The `--range` option is only supported when formatting a single file but the specified paths resolve to {} files.

What it means

`ruff format --range <start:end>` reformats a byte range inside a single file, so the command aborts when the given paths resolve to more than one Python file (the count of resolved files is included in the message).

Source

Thrown at crates/ruff/src/commands/format.rs:88

/// Format a set of files, and return the exit status.
pub(crate) fn format(
    cli: FormatArguments,
    config_arguments: &ConfigArguments,
    pyproject_config: &PyprojectConfig,
) -> Result<ExitStatus> {
    let mode = FormatMode::from_cli(&cli);
    let files = resolve_default_files(cli.files, false);
    let (paths, resolver) = project_files_in_path(&files, pyproject_config, config_arguments)?;

    let output_format = pyproject_config.settings.output_format;

    if paths.is_empty() {
        warn_user_once!("No Python files found under the given path(s)");
        return Ok(ExitStatus::Success);
    }

    if cli.range.is_some() && paths.len() > 1 {
        return Err(anyhow::anyhow!(
            "The `--range` option is only supported when formatting a single file but the specified paths resolve to {} files.",
            paths.len()
        ));
    }

    warn_incompatible_formatter_settings(&resolver);

    // Discover the package root for each Python file.
    let package_roots = resolver.package_roots(
        &paths
            .iter()
            .flatten()
            .map(ResolvedFile::path)
            .collect::<Vec<_>>(),
    );

    let caches = if cli.no_cache {
        None

View on GitHub (pinned to 672bb4edf0)

Solutions

  1. Pass exactly one file: `ruff format --range 0:100 path/to/file.py`
  2. Drop `--range` to format every resolved file
  3. Narrow the path or glob so only one Python file matches

Example fix

# before
ruff format --range 1:50 src/

# after
ruff format --range 1:50 src/main.py
Defensive patterns

Strategy: validation

Validate before calling

n=$(find "$dir" -name '*.py' -o -name '*.pyi' | wc -l)
if [ "$n" -ne 1 ]; then
  echo "--range needs exactly one file (found $n)" >&2
  exit 1
fi
ruff format --range "$range" "$dir"

Prevention

When it happens

Trigger: `ruff format --range 1:20 src/` when src/ contains two or more Python files; passing multiple files or a wide glob together with `--range`.

Common situations: Editor/IDE integrations forwarding a selection range plus a directory; scripts written for one file later pointed at a folder; globs that unexpectedly match extra .py files.

Related errors


AI-assisted analysis of astral-sh/ruff@672bb4edf0 (2026-08-16). Data as JSON: /api/errors/1dc5c19f40243340. Report an issue: GitHub.