[ty] Fix unnecessary ty:ignore comments inserted by --add-ignore for diagnostics starting on the same line by MichaReiser · Pull Request #24651 · astral-sh/ruff (original) (raw)

Summary

This PR fixes an issue where --add-ignore inserted a redundant ty: ignore suppression, resulting in a unused-ignore-comment warning.

diag["home_assistant"]["entities"] = sorted(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ wider range
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ narrower range
    diag["home_assistant"]["entities"], key=lambda ent: ent["entity_id"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)  # end of the wider range
^ wider range

ty emits two diagnostics invalid-assignment diagnostics in this example:

  1. One, whose suppression range extends to the narrower range, that is, it only covers diag["home_assistant"]["entities"] = sorted(
  2. One, whose suppression range covers the entire statement (because the invalid-assignment intentionally extends to cover the entire right-hand side expression.

ty first added the suppression for 1. by inserting a new suppression comment at the end of the narrower range. That is, it fixed the above code to:

diag["home_assistant"]["entities"] = sorted( # ty:ignore[invalid-assignment] diag["home_assistant"]["entities"], key=lambda ent: ent["entity_id"] range )

This, on its own, is sufficient to suppress both diagnostics (because ty allows suppressing diagnostics on both the diagnostic's start and end lines).

However, ty inserted a second suppression for 2, by adding a new suppression comment at the end of the wider range, resulting in:

diag["home_assistant"]["entities"] = sorted( # ty:ignore[invalid-assignment] diag["home_assistant"]["entities"], key=lambda ent: ent["entity_id"] range ) #ty:ignore[invalid-assignment]

ty already accounts for the case that a diagnostic can both be suppressed by inserting a suppression at its start or end line, and it deduplicates those suppressions. However, it didn't account for the case where inserting an end suppression (for the narrower range) results in a start-line suppression for a diagnostic with a wider range.

This PR extends the deduplication logic to account for this case.

Test Plan

Added test.

Ran ty check --add-ignore on homeassistant core and verified that it no longer results in any unused ignore comment warnings