Solve Python Unresolved Reference in Inner Methods Jan 27th 2022 Words: 132

Problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def main():
var = 0
arr = []

def inner():
arr.append(1) # works fine
var += 1 # does not work

inner()


if __name__ == "__main__":
main()

If run the above snippet, an error would be thrown UnboundLocalError: local variable 'var' referenced before assignment

Solotion

Python nonlocal keyword is used to make the variable which refers to the variable bounded in the nearest scope. Scope to which variable it bound should not be global or local scope. In Python nonlocal variable follows different behavior from identical binding, It searches for variables in another scope. The nonlocal variable is used in the nested function. nonlocal variable is used in declaring the variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def main():
var = 0
arr = []

def inner():
arr.append(1)
nonlocal var # nonlocal declaration
var += 1

inner()


if __name__ == "__main__":
main()