[New-bugs-announce] [issue34939] Possibly spurious SyntaxError: annotated name can't be global

Rohan Padhye report at bugs.python.org
Mon Oct 8 21:58:38 EDT 2018


New submission from Rohan Padhye <rohanpadhye at cs.berkeley.edu>:

The following code when run as a script file gives syntax error:

```
def set_x():
    global x
    x = 1

x:int = 0   # SyntaxError: annotated name 'x' can't be global
```

PEP 526 does not seem to forbid this. The error message "annotated name [...] can't be global" is usually seen when using the `global x` declaration *in the same scope* as an annotated assignment. In the above case, the annotated assignment is outside the function scope, yet Python 3.7 gives a syntax error.


Is this a bug in CPython? Or should the PEP 526 document say something about forward references?

Interestingly, if the above program is run in interactive mode, there is no syntax error. 

In interactive mode:
```
>>> def set_x():
...     global x
...     x = 1
... 
>>> x:int = 0
>>> set_x()
>>> print(x)
1
```

Further, forward references work fine with `nonlocal`. For example, the following works fine both as a script file and in interactive mode:
```
def outer():
    def inner():
        nonlocal y
        y = 1
    y:int = 0
```

I don't see why a forward reference in `global` is a problem.

----------
components: Interpreter Core
messages: 327378
nosy: rohanpadhye
priority: normal
severity: normal
status: open
title: Possibly spurious SyntaxError: annotated name can't be global
type: behavior
versions: Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34939>
_______________________________________


More information about the New-bugs-announce mailing list