mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-30 13:51:16 +00:00
allow reads of "free" variables to refer to a global
declaration
Previously this worked if there was also a binding in the same scope as the `global` declaration (probably almost always the case), but CPython doesn't require this. This change surfaced an error in an existing test, where a global variable was only ever declared and bound using the `global` keyword, and never mentioned explicitly in the global scope. @AlexWaygood suggested we probably want to keep that requirement, so I'm adding an a new test for that on top of fixing the failing test.
This commit is contained in:
parent
3b4667ec32
commit
5f2e855c29
2 changed files with 28 additions and 2 deletions
|
@ -44,6 +44,24 @@ def f():
|
|||
reveal_type(x) # revealed: str
|
||||
```
|
||||
|
||||
## Reads terminate at the `global` keyword in an enclosing scope, even if there's no binding in that scope
|
||||
|
||||
_Unlike_ variables that are explicitly declared `nonlocal` (below), implicitly nonlocal ("free")
|
||||
reads can come from a variable that's declared `global` in an enclosing scope. It doesn't matter
|
||||
whether the variable is bound in that scope:
|
||||
|
||||
```py
|
||||
x: int = 1
|
||||
|
||||
def f():
|
||||
x: str = "hello"
|
||||
def g():
|
||||
global x
|
||||
def h():
|
||||
# allowed: this loads the global `x` variable due to the `global` declaration in the immediate enclosing scope
|
||||
y: int = x
|
||||
```
|
||||
|
||||
## The `nonlocal` keyword
|
||||
|
||||
Without the `nonlocal` keyword, bindings in an inner scope shadow variables of the same name in
|
||||
|
@ -264,8 +282,8 @@ def f1():
|
|||
|
||||
@staticmethod
|
||||
def f3():
|
||||
# This scope declares `x` nonlocal and `y` as global, and it shadows `z` without
|
||||
# giving it a type declaration.
|
||||
# This scope declares `x` nonlocal, shadows `y` without a type declaration, and
|
||||
# declares `z` global.
|
||||
nonlocal x
|
||||
x = 4
|
||||
y = 5
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue