0

Why does this not work in python?, where I can access the enclosing scope (here global scope) when there are no other references to the same variable but can't when there are.

Does the interpreter look further down the function first before for the variable definition, finds it so assumes it is only a local variable which hasn't yet been assigned a value? What's the run order of the interpreter here?

> a = 5
> a
Out[3]: 
5
> def closure():
    print(a)

> closure()
5
> def closure():
    print(a)
    a = "another"
    return a
> closure()

UnboundLocalError: local variable 'a' referenced before assignment
Yunti
  • 6,761
  • 12
  • 61
  • 106

1 Answers1

0

Add global a to the first line of the function.

hsfzxjy
  • 1,242
  • 4
  • 14
  • 22