diff --git a/crates/ruff/src/checkers/ast/mod.rs b/crates/ruff/src/checkers/ast/mod.rs index 23ceea36b5..693a8c759c 100644 --- a/crates/ruff/src/checkers/ast/mod.rs +++ b/crates/ruff/src/checkers/ast/mod.rs @@ -210,7 +210,7 @@ where &stmt.node, StmtKind::Import { .. } | StmtKind::ImportFrom { .. } ) { - if self.ctx.scope_id.is_global() && self.ctx.current_stmt_parent().is_none() { + if self.ctx.at_top_level() { self.importer.visit_import(stmt); } } diff --git a/crates/ruff_python_semantic/src/context.rs b/crates/ruff_python_semantic/src/context.rs index 9212dcbd68..29bc3a4fe5 100644 --- a/crates/ruff_python_semantic/src/context.rs +++ b/crates/ruff_python_semantic/src/context.rs @@ -398,6 +398,15 @@ impl<'a> Context<'a> { self.stmts.ancestor_ids(node_id).map(|id| self.stmts[id]) } + /// Return `true` if the context is at the top level of the module (i.e., in the module scope, + /// and not nested within any statements). + pub fn at_top_level(&self) -> bool { + self.scope_id.is_global() + && self + .stmt_id + .map_or(true, |stmt_id| self.stmts.parent_id(stmt_id).is_none()) + } + /// Returns `true` if the context is in an exception handler. pub const fn in_exception_handler(&self) -> bool { self.in_exception_handler