In this section we will namespace and scope of the variables in Python.
A name in Python can be referred as an identifier that is used to give a simple name to an object. Everything in Python is considered to be an Object and hence names in Python are used to access those objects. For example if we store a value in a variable x as:
x= 1, then 1 is the object that will be stored in the memory and x is the name that is given to this object. The built in function id () is used to get the address of an object from the memory in Python.
Consider the following example in which we have used the id () function to know that where a specific object is stored:
>>> x = 3
>>> print (‘id (3) =’, id (3))
>>> print (‘id (x) =’, id (x))
id (3) = 1529108784
id (x) = 1529108784
It can be seen in the above example that both the object and the variable or they are saved in different memory locations.
A namespace in Python is a collection of names. A namespace in Python can be considered as the mapping of every name that is defined by the user and is specified to a certain object in the program. When the Python interpreter is started, a namespace with all the built in functions of Python is created and remains until we exit from the interpreter.
As a namespace is created when the interpreter is started therefore, we can easily use the built in functions such as print () function. Each module in Python is defined by a different global namespace. A local namespace in Python can be created when a function is defined.
The scope of variable can be defined as the space in the program in which the namespace can be accessed directly without using prefix. There are total three scopes of variables in Python.
- Scope of functions having local names.
- Scope of module having global names.
- The outermost scope that contains built in names.
When the user makes a reference inside a function then the names will be searched in the local namespace first then it is searched in the global namespace and at the end in the built in namespace. But if nested functions are used that is a function inside another function then a new scope will be nested inside the local scope.
>>> def func1():
y = 13
>> z = 14
In the above example, the variable z is in the global namespace and the variable x is in the local namespace of the function func1. The variable is in the local namespace of the function names func2. When we are in the function named func2 or in the inner function of the nested function, we can assign any value to the variable y but can only read the values of the variables x and y.
If we are in the inner function of the nested function and try to assign a value to the variable x, then a new variable named x will be created in the local namespace and this variable will be different to the non local variable x that was created in the outer function of the nested function.