+ 2
Can someone explain this output between global and local variables?
6 Answers
+ 3
I may be completely wrong about this but just as a guess, I believe it's because you called x as a variable rather than a string in the second foo function.
So because it is being used in foo when you're trying to see if it's a global variable, it is now also a local variable because it's being "called down" in that space and thus being added to the dictionary for the local function.
Because the locals function returns a dictionary with the variable name as the key in string format, and then the value of the same variable as the value of the key.
So essentially the result of locals in your second foo function is:
{ 'x': 1 }
You can test it out by adding a print statement after the first one in the second foo function: print(locals())
+ 3
Justice you are completely right
+ 1
Lookup "namespaces python"
globals() gives you all the names and values of variables in the global namespace.
locals() (When called within a function or method) gives you all the names and values of variables WITHIN the function or method, i.e. their local namespace
What do you have a question about exactly?
- 2
Nh