ruff/crates/ruff_python_semantic/src
Brent Westbrook 6d3b1d13d6
[pylint] Detect global declarations in module scope (PLE0118) (#17411)
Summary
--

While going through the syntax errors in [this comment], I was surprised
to see the error `name 'x' is assigned to before global declaration`,
which corresponds to [load-before-global-declaration (PLE0118)] and has
also been reimplemented as a syntax error (#17135). However, it looks
like neither of the implementations consider `global` declarations in
the top-level module scope, which is a syntax error in CPython:

```python
# try.py
x = None
global x
```

```shell
> python -m compileall -f try.py
Compiling 'try.py'...
***   File "try.py", line 2
    global x
    ^^^^^^^^
SyntaxError: name 'x' is assigned to before global declaration
```

I'm not sure this is the best or most elegant solution, but it was a
quick fix that passed all of our tests.

Test Plan
--

New PLE0118 test case.

[this comment]:
https://github.com/astral-sh/ruff/issues/7633#issuecomment-1740424031
[load-before-global-declaration (PLE0118)]:
https://docs.astral.sh/ruff/rules/load-before-global-declaration/#load-before-global-declaration-ple0118
2025-04-25 08:37:16 -04:00
..
analyze Upgrade to Rust 1.86 and bump MSRV to 1.84 (#17171) 2025-04-03 15:59:44 +00:00
cfg Control flow: return and raise (#17121) 2025-04-03 08:30:29 -05:00
model Upgrade Rust toolchain to 1.83 (#14677) 2024-11-29 12:05:05 +00:00
binding.rs [ruff] Fix false positive on global keyword (RUF052) (#15235) 2025-01-14 08:36:40 +01:00
branches.rs Add branch detection to the semantic model (#6694) 2023-08-19 21:28:17 +00:00
context.rs Remove separate ReferenceContext enum (#4631) 2023-05-24 15:12:38 +00:00
definition.rs Make setting and retrieving pydocstyle settings less tedious (#12582) 2024-07-31 10:39:33 +01:00
globals.rs Refine SemanticModel lifetime bounds (#10221) 2024-03-04 09:21:13 +01:00
imports.rs Config error only when flake8-import-conventions alias conflicts with isort.required-imports bound name (#15918) 2025-02-04 17:05:35 -06:00
lib.rs Control flow graph: setup (#17064) 2025-04-01 05:53:42 -05:00
model.rs [pylint] Detect global declarations in module scope (PLE0118) (#17411) 2025-04-25 08:37:16 -04:00
nodes.rs Remove customizable reference enum names (#15647) 2025-01-21 13:46:31 -05:00
reference.rs [ruff] Avoid emitting assignment-in-assert when all references to the assigned variable are themselves inside asserts (RUF018) (#14661) 2024-11-29 13:36:59 +00:00
scope.rs Refactor semantic syntax error scope handling (#17314) 2025-04-09 14:23:29 -04:00
star_import.rs Make ImportFrom level just a u32 (#11170) 2024-04-26 20:38:35 -06:00