Globals and Locals
In the previous lesson, I showed you the basic usage of
eval(). In this lesson, I’m going to show you the additional parameters for globals and locals and how to use it with the built-in
I’ve added something to the global namespace. Running the
locals() function has a similar result. Now you might ask yourself, “Why is
'x': 3 here?” Well, because I’m not inside of a function, the
x is in both the global and the local namespace.
And now I’m going to run it. And here you can see the difference. The
globals() section, which was printed first, now includes the
'x': 3 from the first global declaration, also the definition of the
show_locals() function, and then below the line of hyphens, you can see the
locals() result, which is just
inside is local to just the
show_locals() function. It doesn’t show up in the global space and nothing from the global space shows up in the local space. Once again, here’s the signature of the
02:31 It takes an expression, which I’ve introduced you to in previous lessons, as well as optional global and local dictionaries. These dictionaries specify the global and local context for the evaluation inside of the call. Let me show you these in practice.
The global dictionary can also reference things that are just specific to the
eval(). The actual global namespace does not have a
z inside of it, but because I’ve put it inside of this dictionary, it is within the
Now, that’s interesting. It still worked. It turns out that builtins are a special case. If you do not explicitly override them, the
eval() call automatically adds
builtins to the global namespace.
In this case, I’ve overridden that
builtins call to be empty, and now
pow() is no longer defined and an error happens. In addition to affecting the global namespace, you can also affect the local namespace.
This is similar to before, but this time I’m defining
x inside of the local namespace and leaving the global namespace empty. The
x here has picked up a value of
100 from the assignment of the first line I made in the REPL. So although that’s in the REPL’s global namespace, it’s being passed into the local namespace of the
But all of the functions—
__import__()—anything that interprets code in Python has these namespaces. So although it doesn’t make much of a difference here, it’s there for consistency and to stop weird little corner cases if you happen to be calling a function that uses
globals() underneath. One last thing to point out. Because
eval() is kind of old, it doesn’t actually support keyword arguments passed in.
locals explicitly doesn’t work. If you want to set a value for
locals, you have to pass in
globals as well, which is why I’ve been passing in that empty dictionary when I was showing you how to use
locals up until now.
Become a Member to join the conversation.