Search code examples
python-3.xsyntax-errorglobal-variables

Why can't an annotated variable be global?


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?


Solution

  • This has been explained in PEP-526:

    It is illegal to attempt to annotate variables subject to global or nonlocal 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 and nonlocal 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.