When I try to reassign a variable inside a function, I get error of UnboundLocalError
. Following is a snippet of my problem.
global_variable = 'a'
def abc():
print(global_variable)
global_variable = 'b'
abc()
when I execute it then I get the following:
Traceback (most recent call last):
File "/Users/arghyasaha/hobby_project/python_experiment/python_experiment/random_experiment/del_me.py", line 7, in <module>
abc()
File "/Users/arghyasaha/hobby_project/python_experiment/python_experiment/random_experiment/del_me.py", line 4, in abc
print(global_variable)
UnboundLocalError: local variable 'global_variable' referenced before assignment
To solve this issue we can use global
keyword like this
global_variable = 'a'
def abc():
global global_variable
print(global_variable)
global_variable = 'b'
abc()
I am looking for an explanation, to this behaviour, it seems somewhat similar to hoisting concept in javascript. I did find few resources, like source1, source2 but none of them explained well enough. Can someone give a proper explanation with what exactly happens under the hood in python?