UnboundLocalError | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

UnboundLocalError

I have 2 global variables, an int g_int and a dictionary g_dict. The dictionary can be seen and modified from inside a class c constructor. The int no: if I uncomment the line inside the constructor which tries to increment g_int, I get an UnboundLocalError exception: local variable g_int referenced before assigned. Why this strange behaviour? https://code.sololearn.com/cqr9S4IMefg7/?ref=app

25th Jul 2019, 6:56 PM
Bilbo Baggins
Bilbo Baggins - avatar
3 Answers
+ 2
Cbr✔[ Not Active ] please uncomment line 6 and you will see the error
25th Jul 2019, 7:37 PM
Bilbo Baggins
Bilbo Baggins - avatar
+ 1
That is a nice bypass! But it is strange anyway. If you "print(globals())" inside the constructor, g_int is listed with the correct value.
25th Jul 2019, 7:56 PM
Bilbo Baggins
Bilbo Baggins - avatar
+ 1
Ok, now I see... With the help of your suggestion Cbr✔[ Not Active ] I searched for "global keyword" and I found the solution. A global variable inside a function can be accessed but cannot be modified (without the "global" re-declaration). A dictionary is a different thing: it is not modified, it is just expanded.
25th Jul 2019, 8:09 PM
Bilbo Baggins
Bilbo Baggins - avatar