Running
def function():
global global_values
global_values: str = []
gives
SyntaxError: annotated name 'global_values' can't be global
Is there any reason for this?
This has been explained in PEP-526:
It is illegal to attempt to annotate variables subject to
global
ornonlocal
in the same function scope:
def f():
global x: int # SyntaxError
def g():
x: int # Also a SyntaxError
global x
The reason is that
global
andnonlocal
don't own variables; therefore, the type annotations belong in the scope owning the variable.
The solution is to annotate the variable outside the function (i.e., in the global namespace), and remove type annotations inside the function's scope.