Skip to content

REPL incorrectly accepts errorneous global statement #137376

@matthewyu0311

Description

@matthewyu0311

Bug report

Bug description:

According to the docs on global statement,

The global statement applies to the entire scope of a function or class body. A SyntaxError is raised if a variable
is used or assigned to prior to its global declaration in the scope.

this is clearly a syntax error (global after assignment), yet REPL accepts it.

>>> x = 0; global x; x = 1; print(x)
1
>>> x = 0
... global x
... x = 1
... print(x)
... 
1

But if put into a module file or command line python -c "x=0; global x; x=1", it is correctly rejected.

exec also rejects it:

>>> exec("x = 0; global x; x = 1; print(x)")
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    exec("x = 0; global x; x = 1; print(x)")
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 1
SyntaxError: name 'x' is assigned to before global declaration

In any of the above cases the global is redundant, yet only the REPL ignores it silently. If this is intended behavior of the REPL, I think the REPL should give a SyntaxWarning pointing out this syntax would be invalid in other cases.

CPython versions tested on:

3.13

Operating systems tested on:

Windows

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13bugs and security fixes3.14bugs and security fixes3.15new features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)release-blockerstdlibPython modules in the Lib dirtopic-replRelated to the interactive shelltype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions