All Courses

Namespaces and Scope in Python

Pallavi Dhotre

a year ago

namespaces and scope in python
Table of Contents 
  • Introduction
  • Namespaces in Python
            1. Definition 
            2. Python Namespace Example
            3. Types Of Namespaces 
                 1.  Built-in Namespace
                 2.  Global Namespace
                 3.  Local Namespace
                 4.  Create namespace
  • Scopes in Python
                1. Local Scope
                2. Global Scope
                3. Built-in Scope
                4. Function Inside Function 

Introduction 

          In this article, we are going to know about the namespaces in python, types of namespaces, and scopes in python. In python programming, everything is considered an object. Name is nothing but the identifier of an object. And space is an address in the main memory associated with that object. We can define namespace as a collection of names associated with the address in the main memory. There are three types of namespaces in python - Built-in Namespace, Global Namespace, and Local Namespace. Each lower namespace can access the upper namespaces. And the scope of variables in python depends on the namespaces. We will know more about this in the sections given below:

Namespaces in Python

1. Definition 

          Every entity in python is considered an object. We give some names to every object like variable, class, and function for identification. Often these names are known as identifiers in python. So, the name is nothing but the identifier. All these names and where we use value are stored in the main memory at a unique location. This location is known as space. So the location allocated to an object name and its value is known as python namespaces. Python also maintains its namespace that is known as a python dictionary. All namespaces in python are like dictionaries in which names are considered as keys, and dictionary values are the actual values associated with those names.

2. Python Namespace Example

          File directories in a computer system are the best example of namespaces. Files may have the same names but different data and are stored at various locations. If we know the exact address of the file, we can find the file accurately. The telephone directory is a good real-time example for the namespace. If we try to search a phone number of a person named John, there are multiple entries, and it will be difficult to find the right one. But if we know the surname of John, we can see the correct number. In this case, a person's name is a name or identifier in python, and space depends on the person’s location.  

3. Types of Namespaces in Python

Types of Namespaces in Python 

1. Built-in Namespace

          When we run the Python interpreter without creating any user-defined function, class, or module, some functions like input(), print(), type() are always present. These are built-in python namespaces.
name=input("Enter your name:") #input() is built-in function
print(name) #print() is built-in function
In the above code we are using input() and print() without creating any function or without accessing any module. 

2. Global Namespace

          When we create a module, it creates its namespaces, and these are called global namespaces. The global namespace can access built-in namespaces.
x=10 #variable declared in a global namespace with the global scope of variable in python
def f1(): #function definition
  print(x) #variable accessed inside the function
f1()
In the code given above, the variable x is declared in a global namespace and has a global scope of variable in python.

3. Local Namespace

          When we create a function, it creates its namespaces, and these are called local namespaces. A local namespace can access global as well as built-in namespaces.
def f1(): #function definition
    print("function start ")
    def f2():
        var = 10   # local scope of variable in python
        print("local function, value of var:",var)
    f2()
    print("Try printing var from outer function: ",var)
f1()
In the code given above, the variable var is declared in a local namespace and has a local scope of variable in python. 
Output:
function start 
local function, value of var: 10
Traceback (most recent call last):
  File "<string>", line 10, in <module>
  File "<string>", line 9, in f1
NameError: name 'var' is not defined
Now let’s deep dive into the concept How to create a namespace? With example

4. Create namespace

x='I am Global'  #global namespace and global scope of variable in python
def f1():        #function definition
    y='I am Local' # local namespace and local scope of variable in python 
    print(x)       #accessing global namespace from local namespace
    print(y)       #accessing local namespace, we use
f1()      #function calling
print('I am Built-in') # print() is a built-in namespace
          In the above example, we have used a built-in namespace i.e. print() which is accessed by global and local namespace. Also, we have created global namespace x and local namespace y. 
Output
I am Global

I am Local

I am Built-in

Scopes in Python

          The lifetime of the object depends on the scope of the object. Once the lifetime of the object comes to the end scope of variables in python also ends.  Scopes in python are nothing but the part or portion of the program where namespace can be accessed directly.

Types of Scope

1. Local Scope

          If we create a variable inside the function, then the scope of the variable in python is local.
Example :
def fun1():
  x = "local"  # local scope
  print(x)

fun1()
Output:
local

2. Global Scope

          If we create a variable inside the module, then that variable has a global scope in python.
Example:
x = "Global"

def fun1():
  print(x)

fun1()

print(x)
Output :
Global
Global

3. Built-in Scope

          When we don’t create any module or user-defined function and still can access the methods like print(), type(), input(), then it is a built-in scope. When a script is run that created or loaded built-in scope.

4. Function Inside Function

          The variable is defined under the function, which is available only inside that function and nested function.
Example:
def fun1():
  x = "outer Function"
  def fun2():
    print(x)
  fun2()

fun1()
Output:
outer Function
Let’s see an example for the scope of variable in python
x='I am a global variable I have global scope' #global namespace this has a global scope in python
def f1():        #function definition
    y='I am a Local variable I have local scope' # local namespace
    print(x)       #accessing global namespace from local namespace
    print(y)       #accessing local namespace
f1()      #function calling
print('I am a Built-in function I have built-in scope') # print() is a built-in namespace
In the above example, variable x is global, variable y is local, and the print() function is built-in.  The output of the above program is:
I am a Global variable I have global scope
I am a Local variable I have local scope
I am a Built-in function I have built-in scope

Summary

          In this article, we have learned about namespaces and scope in python. Also, we have learned about the types of namespaces in Python with examples. In python programming, everything is considered an object. Name is nothing but the identifier of an object. And space is an address in the main memory associated with that object. We can define namespace as a collection of names associated with the address in the main memory. There are three types of namespaces in python -  Built-in Namespace, Global Namespace, and Local Namespace. The scope of variables in python is associated with the namespace in python. 
If you are interested in gaining more knowledge on Python, we recommend joining InsideAIML's Artificial Intelligence Master Program. The 8-month course comprises 475+ High-Quality Lectures, 150+ hours of course content, 20+ Real-Life Projects, a 6-month internship certificate, and much more. 

Submit Review