[flake8-pyi] Mark unaliased-collections-abc-set-import fix as safe (#9679)

## Summary

Prompted by
https://github.com/astral-sh/ruff/issues/8482#issuecomment-1859299411.
The rename is only unsafe when the symbol is exported, so we can narrow
the conditions.
This commit is contained in:
Charlie Marsh 2024-01-29 09:56:17 -08:00 committed by Zanie Blue
parent c2bf725086
commit b81fc5ed11
3 changed files with 22 additions and 8 deletions

View file

@ -1,4 +1,4 @@
use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation};
use ruff_diagnostics::{Applicability, Diagnostic, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_semantic::Imported;
use ruff_python_semantic::{Binding, BindingKind};
@ -29,6 +29,12 @@ use crate::renamer::Renamer;
/// ```python
/// from collections.abc import Set as AbstractSet
/// ```
///
/// ## Fix safety
/// This rule's fix is marked as unsafe for `Set` imports defined at the
/// top-level of a module. Top-level symbols are implicitly exported by the
/// module, and so renaming a top-level symbol may break downstream modules
/// that import it.
#[violation]
pub struct UnaliasedCollectionsAbcSetImport;
@ -69,7 +75,15 @@ pub(crate) fn unaliased_collections_abc_set_import(
diagnostic.try_set_fix(|| {
let scope = &checker.semantic().scopes[binding.scope];
let (edit, rest) = Renamer::rename(name, "AbstractSet", scope, checker.semantic())?;
Ok(Fix::unsafe_edits(edit, rest))
Ok(Fix::applicable_edits(
edit,
rest,
if scope.kind.is_module() {
Applicability::Unsafe
} else {
Applicability::Safe
},
))
});
}
Some(diagnostic)

View file

@ -9,7 +9,7 @@ PYI025.py:10:33: PYI025 [*] Use `from collections.abc import Set as AbstractSet`
|
= help: Alias `Set` to `AbstractSet`
Unsafe fix
Safe fix
7 7 |
8 8 |
9 9 | def f():
@ -29,7 +29,7 @@ PYI025.py:14:51: PYI025 [*] Use `from collections.abc import Set as AbstractSet`
|
= help: Alias `Set` to `AbstractSet`
Unsafe fix
Safe fix
11 11 |
12 12 |
13 13 | def f():

View file

@ -11,7 +11,7 @@ PYI025.pyi:8:33: PYI025 [*] Use `from collections.abc import Set as AbstractSet`
|
= help: Alias `Set` to `AbstractSet`
Unsafe fix
Safe fix
5 5 | from collections.abc import Container, Sized, Set as AbstractSet, ValuesView # Ok
6 6 |
7 7 | def f():
@ -31,7 +31,7 @@ PYI025.pyi:11:51: PYI025 [*] Use `from collections.abc import Set as AbstractSet
|
= help: Alias `Set` to `AbstractSet`
Unsafe fix
Safe fix
8 8 | from collections.abc import Set # PYI025
9 9 |
10 10 | def f():
@ -52,7 +52,7 @@ PYI025.pyi:16:37: PYI025 [*] Use `from collections.abc import Set as AbstractSet
|
= help: Alias `Set` to `AbstractSet`
Unsafe fix
Safe fix
13 13 | def f():
14 14 | """Test: local symbol renaming."""
15 15 | if True:
@ -130,7 +130,7 @@ PYI025.pyi:44:33: PYI025 [*] Use `from collections.abc import Set as AbstractSet
|
= help: Alias `Set` to `AbstractSet`
Unsafe fix
Safe fix
41 41 |
42 42 | def f():
43 43 | """Test: nonlocal symbol renaming."""