Python Namespace and Scope,



Namespace
=========

  • Every name introduced in a python program has a place where it lives and can be looked for. This is its namespace. 
  • Consider it as a box where a variable name mapped to object is placed. Whenever the variable name is referenced, this box is looked out to get corresponding object. 
  • For example, functions defined using def  have namespace of the module in which it is defined. And so 2 modules can define function with same name. 
  • Modules and namespace go hand in hand. 
  • Each module introduces a namespace. 
  • Namespace helps in reusing name by avoiding name collision. 
  • Classes and functions are other namespace constructs


Scope
=====
  • Scope for names introduced in a python program is a region where it could be used, without any qualification. That is, scope is region where the unqalified reference to a name can be looked out in the namespace to find the object. 
  • During execution, when a name is referred, python uses LEGB rule to find out the object. 
  • It starts looking out first into the local namespace. Then it searches name in enclosed namespace created by nested def and lambda. Then into global namespace which is the module in which it is defined and then finally into built-in namespace.
Example 1:
>>> def addxy(x,y):        # x, y are local. addxy is global
...     temp=x+y           # temp is local
...     print temp
...     return temp
...
>>> addxy(1,2)
3
3

 
Example 2:
>>> total = 0           # total is global
>>> def addxy(x,y):
...     global total
...     total = x+y
...
>>> x
100
>>> y
200
>>> addxy(x,y)
>>> total
300




No comments:

Post a Comment