Enclosing and Local Namespaces
Next, it declares a variable called
s, after which it declares an enclosed function called
g(), which again prints where it starts, declares a variable, and prints where it ends. Finally, within the enclosing function
f(), you call the function
g(). And finally, you print where the function
f() ends. So now if you want to know what the local namespace contains, you can do this by printing the return value of the
locals() function. In this case, let’s see what the local namespace contains after the function
f() started and a variable
s is declared.
A nice thing about local namespaces is that you also have access to the local namespace of the enclosing function within the enclosed function. So when you would like to print the value of
s within the function
g(), you can do that because the function
g() has access to all names within the namespace of its enclosing function. So, again, you run the module and you call the function
And now you see that you were able to access
s is also copied to the namespace of the enclosed function
g(). And that brings us to the end of this section about the types of namespaces in Python. In the next section of this course, you will learn about variable scope.
Become a Member to join the conversation.