diff --git a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__semantic_syntax_error_annotated_global.py_3.14.snap b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__semantic_syntax_error_annotated_global.py_3.14.snap index c8d3eb32f6..98735e9b5d 100644 --- a/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__semantic_syntax_error_annotated_global.py_3.14.snap +++ b/crates/ruff_linter/src/snapshots/ruff_linter__linter__tests__semantic_syntax_error_annotated_global.py_3.14.snap @@ -44,3 +44,13 @@ invalid-syntax: annotated name `d` can't be global 21 | 22 | e: int = 1 | + +invalid-syntax: annotated name `g` can't be global + --> resources/test/fixtures/semantic_errors/annotated_global.py:29:1 + | +27 | f: int = 1 # okay +28 | +29 | g: int = 1 + | ^ +30 | global g # error + | diff --git a/crates/ruff_python_parser/src/semantic_errors.rs b/crates/ruff_python_parser/src/semantic_errors.rs index 5fdf41f0c2..29bc07c47c 100644 --- a/crates/ruff_python_parser/src/semantic_errors.rs +++ b/crates/ruff_python_parser/src/semantic_errors.rs @@ -300,12 +300,15 @@ impl SemanticSyntaxChecker { visitor.visit_expr(annotation); } if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() { - if ctx.global(id.as_str()).is_some() && ctx.in_function_scope() { - Self::add_error( - ctx, - SemanticSyntaxErrorKind::AnnotatedGlobal(id.to_string()), - target.range(), - ); + if let Some(global_stmt) = ctx.global(id.as_str()) { + let global_start = global_stmt.start(); + if ctx.in_function_scope() || target.start() < global_start { + Self::add_error( + ctx, + SemanticSyntaxErrorKind::AnnotatedGlobal(id.to_string()), + target.range(), + ); + } } } }