Navigating Namespaces
00:00 And what about namespaces? Scopes and namespaces are very closely related. The simplest way to think about it is that scope describes the names available in any given location in your program.
00:11 Alternatively, a namespace is some object in code that you can access those names from, and you’ll see how to access the namespaces of scopes throughout this course.
00:22 In short, scopes determine where in your program a name is accessible, and are areas where names are created or accessed. Namespaces, on the other hand, determine how names in a program are stored, and they are the Python dictionaries, mapping names to objects.
00:38
One way to look at them directly would be to access them from the special dunder .__dict__
attribute of modules, functions, or classes.
00:46
Pop open the REPL and we’ll look at a quick example of how to view a namespace using the dunder .__dict__
attribute of a module.
00:54
Here we are in a fresh REPL session. There are already a few names in the global scope, and you can view them by calling the dir()
function with no arguments.
01:03 This returns a list with the names of some special objects Python uses internally as indicated by their leading and trailing double underscores, often shortened to dunder.
01:12
Since you want to view a namespace, you’ll need a module to inspect. Go ahead and import the sys
module, import sys
, and if you call dir()
again, you’ll see at the end of the list is the name sys
, since you just brought it into the global scope with an import statement. The namespace of the sys
module is contained in its dunder .__dict__
attribute.
01:33
Confirm its type by passing it into the type()
function: type(sys.__dict__)
. You’ll see this is nothing more than a Python dictionary.
01:42
Because its contents are actually fairly large, take a look at the dictionary’s keys, sys.__dict__.keys()
.
01:52
Yep, that’s a lot. The output is a list of strings corresponding to all the names defined at the top level of the sys
module. If you wanted to access the object associated with one of those names, you have a couple options.
02:05
The first, well, it’s a dictionary, so you can use accessors directly on the dictionary. Go ahead and grab ps1
, sys.__dict__
['ps1']
in brackets. The result, the REPL’s prompt string. Here, three greater than symbols and a space.
02:23
Of course, the usual technique is simple, dot notation: sys.ps1
. The same result, and a lot less typing. But now you understand that the value is actually retrieved from the namespace, and that namespace represents the module’s global scope.
02:41 But this is just the tip of the iceberg. There’s so much more to learn. Next up, you’ll take a look at each of these scopes in detail, starting with the local scope.
Become a Member to join the conversation.