Understanding Scope
00:00 I finished the last lesson by saying you will make your first contact with Python scope, but if you have written any Python code before, you’ve already worked with a scope—for example, when you assigned a variable in Python—because the concept of scope rules how variables and names are looked up in your code.
00:21 A Python scope determines where a name is visible in your program. Let’s hop over to IDLE to investigate Python scopes.
00:31
Anytime you assign a variable, you create a name. Python uses the location of the name assignment to associate it with a particular scope. For example, if you write total = 5
,
00:48
you assign a value, 5
, to a name, total
, at the top level of a module. Now total
is part of the global Python scope.
00:58
When I type total
, Python knows that it’s 5
. You may wonder how Python finds the variable, and that’s a really good question. Python scopes are implemented as dictionaries that map names to objects. You may not be familiar with the term dictionary in Python context, but you can think of a dictionary like a real dictionary, where you can look up objects and see their values.
01:25
Python scopes are implemented as dictionaries, and these dictionaries are commonly called namespaces. As said before, the variable total
exists in the global scope.
01:36
You can check the global namespace dictionary with the help of the globals()
built-in function.
01:47
The output is the content of the global namespace, and as you can see at the end of this dictionary, you can find the total
name in there and the value, 5
, that the variable has. Okay, so I use the terms scope and namespace.
02:04 When we’re talking about Python scope, we’re talking about a concept, and the namespace dictionary is the implementation of this concept. It’s the implementation of scope. But when you talk to other developers, the terms scope and namespace are often used interchangeably, and that’s totally fine, usually. What’s totally not fine is that I talked about the global scope in a way that may have felt that you should already know what a global scope is. So let’s fix that. In the next lesson, I will talk a bit more about different kind of scopes in Python. For example, the global scope.
Become a Member to join the conversation.