astral-sh/ruff · error

Cannot autofix: reference in the source code (`{}`) is not e

Error message

Cannot autofix: reference in the source code (`{}`) is not equal to the typevar name (`{}`)

What it means

An anyhow bail! in the flake8-pyi custom-typevar-generic-for-self autofix: while replacing typevar references with Self, a reference in the source text does not equal the typevar's name, so applying a textual edit would be wrong. The fix is abandoned and reported as failed.

Source

Thrown at crates/ruff_linter/src/rules/flake8_pyi/rules/custom_type_var_for_self.rs:418

/// Returns a series of [`Edit`]s that modify all references to the given `typevar`.
///
/// Only references within `editable_range` will be modified.
/// This ensures that no edit in this series will overlap with other edits.
fn replace_typevar_usages_with_self<'a>(
    typevar: TypeVar<'a>,
    source: &'a str,
    self_or_cls_annotation_range: TextRange,
    self_symbol_binding: &'a str,
    editable_range: TextRange,
    semantic: &'a SemanticModel<'a>,
    edits: &mut Vec<Edit>,
) -> anyhow::Result<()> {
    let tvar_name = typevar.name(source);
    for reference in typevar.references(semantic) {
        let reference_range = reference.range();
        if &source[reference_range] != tvar_name {
            bail!(
                "Cannot autofix: reference in the source code (`{}`) is not equal to the typevar name (`{}`)",
                &source[reference_range],
                tvar_name
            );
        }
        if !editable_range.contains_range(reference_range) {
            continue;
        }
        if self_or_cls_annotation_range.contains_range(reference_range) {
            continue;
        }
        edits.push(Edit::range_replacement(
            self_symbol_binding.to_string(),
            reference_range,
        ));
    }
    Ok(())
}

View on GitHub (pinned to 26f38c119c)

Solutions

  1. Skip the autofix when a reference's source text does not match the typevar name
  2. Reuse the exact reference span from the semantic model instead of matching by name
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at crates/ruff_linter/src/rules/flake8_pyi/rules/custom_type_var_for_self.rs:418 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of astral-sh/ruff@26f38c119c (2026-09-05). Data as JSON: /api/errors/a00ceed1e39c615d. Report an issue: GitHub.