Namespace and scopes in python
Namespaces
A Namespace Python is a mapping between variable names and objects. There are 3 general kinds of namespaces, main, and builtins namespaces — All the erected in names live then and this namespace is created when the practitioner starts up.
Global namespace — All names declared with the global keyword live then.
Original namespace — The original variables declared within a module or a function belong then.
Compass
A Compass is a textual area of a Python program where a Namespace is directly accessible. Any direct reference to a name with in a compass is directly looked up in the namespace the compass has access to.
Name hunt
When a python law executes, a hunt for a name happens in this order
. Original — Hunt for the name in the original namespace of the function
Enclosing — If it’s not present in the original namespace, hunt for it in the compass of the enclosing function
. Global — If it’s not present there, search the current module’s global namespace
.Main — If it’s not present in global, search the builtins and, main, namespaces.
Non-local and global keywords
Python has two special keywords
- global — Any variable with the global prefix binds that variable to the global namespace
- nonlocal — Any variable with the nonlocal prefix binds the variable to the scope that encloses the local scope but the one that’s inner to global. Or in other words, the scope between global and local.
def scope_test():
def do_local():
spam = "local spam" ## Local scope
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam" ## Enclosing scope
def do_global():
global spam
spam = "global spam" ## Global scope
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
The out put looks like this:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
As you can see from the example, “local spam” is straightforward to catch easily. “nonlocal spam” is bound to the def scope_test() method’s scope. So even after calling do_global() we still see “nonlocal spam” because the execution stops at step 3 (from the Name Search algorithm above) after it finds the name spam.
Comments
Post a Comment