The built-in function
globals() returns a reference to the current global namespace dictionary. You can use it to access the objects in the global namespace.
00:12 Let’s have a look at an example of what it looks like when the main program starts.
Let’s start by having a look at the return type of the
globals() function. As you can see, this is a
dict. Now let’s have a look at the contents of the dictionary that is returned by the
globals() function. As you can see, the interpreter has already created several entries in the global namespace.
00:40 Depending on your Python version and operating system, it may look a little different in your environment, but it should be similar.
Now let’s see what happens to the global namespace dictionary when you add a new variable. You can begin by creating a new variable
x and assigning the value
"foo". Next, you can check the global namespace dictionary by calling the
globals() function, where you will see that the variable
x is added.
This means that instead of accessing the value
x in the usual way, you can also access it directly through the global namespace dictionary. And you can confirm that
x is indeed the same object as
'x' in the global namespace dictionary that is returned by the
globals() function returns the global namespace dictionary, you can also assign variables directly to the global namespace dictionary that is returned by the
globals() function. Now, when you check the contents of the global namespace dictionary, you will see that the value
100 is assigned to the variable
y, and you can access the value of
y in the same way that you would usually access a variable.
02:15 You can also just as easily reassign a new value to a variable using the same method.
Until now, you have only worked with variables that are located in the global namespace of the main program. Now let’s see what happens when you import another module—for example, the
When you look at the global namespace dictionary, then you see that the
datetime module is added. Note that only the
datetime module is added, and not all names the
datetime module contains.
That is because the Python interpreter creates a brand new namespace for every module your program loads with the
03:07 In the next and final lesson of the section, you will learn about local and enclosing namespaces.
Become a Member to join the conversation.