Type hinting (annotation) error with global variable

Viewed 47

This code works fine:

x: int = 10

def f(a):
    global x
    x = 1
    return x + a


print(x, f(7), x)

Producing 10 8 1.

This code does not:

def f(a):
    global x
    x = 1
    return x + a


x: int = 10

print(x, f(7), x)

Producing a SyntaxError: annotated name 'x' can't be global on the type hinting line.

I fail to see the difference. Can you please explain why?

0 Answers
Related