Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Global Namespace

00:00 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.

00:18 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.

00:50 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.

01:13 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.

01:39 Because 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.

02:24 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 datetime module.

02:39 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.

02:54 That is because the Python interpreter creates a brand new namespace for every module your program loads with the import statement.

03:07 In the next and final lesson of the section, you will learn about local and enclosing namespaces.

Gokul Thiruvengadam Rajagopalan on Feb. 25, 2024

difference between dir(globals) and globals()

Become a Member to join the conversation.