+ 3
In which scope a variable inside function exists?
Below x variable is not available in both globals() and locals() Also, printing the variable inside the 'nested function' adds it in the locals() Edit: x is a nonlocal variable for foo() and it is not present in globals() and locals() inside "foo" my question is - how does foo gets access to this variable and why printing it adds the x variable to foo locals() edit: this question is from python "quiz challenges" in Sololearn community section https://code.sololearn.com/c105hE6mO1gD/?ref=app
4 odpowiedzi
+ 5
Per Bratthammar
thanks for the help! 🙌
I also found out, the thing you are explaining is nothing but free variables. Janusz Bujak 🇵🇱 🇺🇦 told me earlier about free variables and closures but I still got confused 😅
I need some practice with closures and free variables. I will ping you and Janusz if I find anything confusing!
Thank you :))
+ 4
Hi, Sandeep !
You created x locally inside bar, so there is where you can use it as a normal variable. You can read x from the inner function foo, but not write to it. You can never reach x from outside the bar function at all, because its not global (so you can’t find x in globals() ).
If you want to write to x from inside foo, you can first write:
nonlocal x
inside foo. After that you can change the (in bar) already existing x. (So now the scope is bigger. You can use x in both foo and bar and find x in locals() in both foo and bar.)
To create x as a global variabel from inside bar, first write:
global x
befor you create it. Now you can find inside globals().
https://code.sololearn.com/ccQQ7TqYNr8d/?ref=app
+ 2
Per Bratthammar
Hi, thanks for the reply!
I think there is something more to it because if I print the variable x inside foo(), it gets added in the "foo locals()"
(see this below)
https://code.sololearn.com/cePV240lARhE/?ref=app
Also, even though it is available in foo() locals i cannot modify it
+ 1
Hi again, Sandeep !
You said you think it’s something more, and often so it is. But here it just reflect that you have looked at x in foo, that was created in bar. When you do that you close the door to create a local variable of x in foo.
If you want use x as a local variable, you must create it in foo before you look at it in foo, otherwise it become connected to x in bar. You can take a look at this:
https://code.sololearn.com/c3k1r2JivWGS/?ref=app