Inspect Locals
00:00
On the right side, you see my IDLE editor where I have the code from the slide, which contains the visit_woods() function, as well as the invitation variable definition, which is “Let’s have a party!” and then the visit_woods() function call. Before continuing, let’s run the code and see if there is any output at all right now. At the moment, this program doesn’t output anything,
00:29
although there is a print() function call in it so let’s check why the print() function call doesn’t get executed. Inside the visit_woods() function where you have the nice bear docstring at the beginning, there is an if statement and the if statement says, if the string my_invitation in locals(), and that’s a function call so it’s locals(), print(my_invitation).
01:01
And interestingly enough, my_invitation at this point is not a string, but a variable name. So there is no error in the output, which is good because we apparently have a variable here that wasn’t defined and there is no output at all.
01:18
And then there is this locals() function call, which is a function that wasn’t defined anywhere here. So what is this locals() function?
01:27
To answer that, let’s just call the function in the root level of the script after the visit_woods() function call, let’s type locals(), save and run the file.
01:47
the locals() function call alone is not enough, but you also need to pass locals() into a print() function call to actually see what the locals() function returns.
02:00
So again, save and run the file. Now with the print() function call and now you see that there is a bunch of output there.
02:12 You can pause the video and explore a little bit what the output exactly is, but I will give you a brief overview.
02:19
Apparently, locals() gives back a dictionary with certain key-value pairs that somehow sound familiar. There is some __name__ key with the __main__ stream as the value.
02:34
There is also a __file__ key, which has the current Python file as a value. And there is also a visit_woods key, which contains the memory address of this function.
02:47
And then there is also an invitation key, which has the value “Let’s have a party!” and that is actually pretty amazing. locals() gives you back the dictionary of all the names that Python knows out of the local scope that it’s in right now.
03:06
So locals() inside the visit_woods() function probably has different values than if you call locals() outside of it.
Become a Member to join the conversation.