Namespaces and Scope in Python


In python we deal with variables, functions, libraries and modules etc. There is a chance the name of the variable you are going to use is already existing as name of another variable or as the name of another function or another method. In such scenario, we need to learn about how all these names are managed by a python program. This is the concept of namespace.

Following are the three categories of namespace

  • Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p>

  • Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the Local namespace.

  • Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn encompasses the local namespace.

Scope in Python

The namespace has a lifetime when it is available. That is also called the scope. Also the scope will depend on the coding region where the variable or object is located. You can see in the below program how the variables declared in an inner loop are available to the outer loop but not vice-versa. Also please note how the name of the outer function also becomes part of a global variable.

Example

prog_var = 'Hello'
def outer_func():
   outer_var = 'x'
   def inner_func():
      inner_var = 'y'
      print(dir(), ' Local Variable in Inner function')

      inner_func()
      print(dir(), 'Local variables in outer function')

      outer_func()
      print(dir(), 'Global variables ')

Running the above code gives us the following result −

Output

['inner_var'] Local Variable in Inner function
['inner_func', 'outer_var'] Local variables in outer function
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'outer_func', 'prog_var'] Global variables

Updated on: 28-Dec-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements