[pyupgrade] Fix false positive on relative imports from local .builtins module (UP029) (#21309)

This commit is contained in:
Dan Parizher 2025-11-07 11:01:52 -05:00 committed by GitHub
parent 6cc3393ccd
commit 6185a2af9e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 19 additions and 1 deletions

View file

@ -0,0 +1,5 @@
from .builtins import next
from ..builtins import str
from ...builtins import int
from .builtins import next as _next

View file

@ -717,7 +717,9 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
}
if checker.is_rule_enabled(Rule::UnnecessaryBuiltinImport) {
if let Some(module) = module {
pyupgrade::rules::unnecessary_builtin_import(checker, stmt, module, names);
pyupgrade::rules::unnecessary_builtin_import(
checker, stmt, module, names, level,
);
}
}
if checker.any_rule_enabled(&[

View file

@ -99,6 +99,7 @@ mod tests {
#[test_case(Rule::UTF8EncodingDeclaration, Path::new("UP009_many_empty_lines.py"))]
#[test_case(Rule::UnicodeKindPrefix, Path::new("UP025.py"))]
#[test_case(Rule::UnnecessaryBuiltinImport, Path::new("UP029_0.py"))]
#[test_case(Rule::UnnecessaryBuiltinImport, Path::new("UP029_2.py"))]
#[test_case(Rule::UnnecessaryClassParentheses, Path::new("UP039.py"))]
#[test_case(Rule::UnnecessaryDefaultTypeArgs, Path::new("UP043.py"))]
#[test_case(Rule::UnnecessaryEncodeUTF8, Path::new("UP012.py"))]

View file

@ -75,7 +75,13 @@ pub(crate) fn unnecessary_builtin_import(
stmt: &Stmt,
module: &str,
names: &[Alias],
level: u32,
) {
// Ignore relative imports (they're importing from local modules, not Python's builtins).
if level > 0 {
return;
}
// Ignore irrelevant modules.
if !matches!(
module,

View file

@ -0,0 +1,4 @@
---
source: crates/ruff_linter/src/rules/pyupgrade/mod.rs
---