Python Namespace – Python Variable Scope

Filed Under: Python

In this tutorial, we are going to learn about Python Namespace and variable scope. In our previous tutorial we learned about Python Custom Exception.

Python Namespace

Namespace is the naming system to avoid ambiguity and to make name uniques. If you’re familiar with other programming language (i.e C/C++/Java), you may know the namespace already.

However, Python’s namespace is implemented using Python Dictionary. That means, namespace is basically a key-value pair. For a given key, there will be a value. In the following sections, we will be discussing about names and their space.

Names and Their Space

If you dissect the word namespace, you will get two things. One is name and another is space. Basically, name is refer to the object name (also knows as identifier). That means, the object you declare is enlarge the namespace. And we have told earlier that the namespace in python is implemented using dictionary. So consider, there are two namespace, nameA and nameB. You can imagine them as


nameA={ ‘var_name1’=object1, ‘var_name2’=object2, …}
nameB={ ‘var_name1’=object3, ‘var_name2’=object5, ‘var_name3’=object6, …}

Here, you can see that, the names can be identical in both namespace but they are different as object. So, namespace allows us to use objects of same name but in different namespace. The following code will provide you the basic idea of namespace.


name = 'Andy'  # define name


def printBob():
   name = 'Bob'  # define name in function
   print('printing from the def: ', name)  # print from function

# the main function
print('printing from the main: ', name)  # print from the main
printBob()  # call the function to print

The produced output will be


printing from the main:  Andy
printing from the def:  Bob

So, you can see that two different object has same name but they are in different scope. Hence, their output differs.

Python Variable Scope

Actually, scope refers the coding region from where the objects of that scope can be accessed. That means, you cannot access the objects of a particular function from anywhere of your code. Like, the following code, you will see that you cannot access an object from outside of its scope.


def printBob():
   var = 'print it'
   print('printing from the function: ', var)  # this will print


# call the function to  print the variable value
printBob()
# try to access the object from outside of its scope
print('printing from the main: ', var)  # this will produce error

So, you will see the output like below.

python namespace, python variable scope example

That means, you can call the function from the main scope but you can’t access the object of that function from the main scope. So, here comes the concept of scope. Basically, you can consider one indented block as its scope. This means, in the following code;


var = 0
name = 'absicsa'

def function_outer():
   # global var    ; no need to declare to call the value
   name = 'nabisco'

   def function_inner():
       global var  # need to declare global to modify the value
       name = 'outlet'
       var = 23
       print('name :',name, ', var :', var)

   print('name :', name, ', var :', var)
   function_inner()

print('name :', name, ', var :', var)
function_outer()

The output of the code will be;

Output showing accessing objects from different python namespace with variable scope

Here, you can see that, the same indented blocks consist of the same namespace. So function_outer() function can be called from the main function’s scope while the function_inner() function can be called from the function_outer() function’s scope. You can also see that global variable can be accessed from the inner namespaces.

Lifetime of the Namespace

The lifetime of the namespace differs because they are created at different time. When the scope ends, the objects that are created in that scope usually deleted. That’s why, you cannot access objects offer inner namespace from the outer namespace because either they are not create yet or the namespace have already been deleted. But in the previous example, you see that you can access the objects from the outer namespace from the inner namespace.

So, that’s all about the Python Namespace. Hope, you understand well. If you have any query, please use the comment box.

References: Official Documentation

Comments

  1. Ashok says:

    Can you please tell me What is the use of global for both with global and without global i’m getting the same output

    var =10
    name=”ashok”
    def outer():
    name=”Kumar”

    def inner():
    global var
    name=”Ashok Kumar”
    var=25
    print(“name:”, name, “var:”, var)

    print(“name:”, name, “var:”,var)
    inner()

    print(“name:”, name, “inner:”, var)
    outer()
    ========================================================================================

    var =10
    name=”ashok”
    def outer():
    name=”Kumar”

    def inner():
    name=”Ashok Kumar”
    var=25
    print(“name:”, name, “var:”, var)

    print(“name:”, name, “var:”,var)
    inner()

    print(“name:”, name, “inner:”, var)
    outer()
    ===================================================================

    1. Prem M S says:

      global is used to change or create global variables in a local context.

      In the same as above program. I have added some print statement in end of the line.

      Scope to be change, while using global – print(“name_last:”, name, “inner:”, var)
      var = 10
      name = “ashok”
      def outer():
      name = “Kumar”
      def inner():
      global var, name
      name = “Ashok Kumar”
      var = 25
      print(“name 1:”, name, “var:”, var)
      print(“name 2:”, name, “var:”, var)
      inner()
      print(“name:”, name, “inner:”, var)
      outer()
      print(“name_last:”, name, “inner:”, var)
      print (“————————————“)

      var = 10
      name = “ashok”
      def outer():
      name = “Kumar”
      def inner():
      name = “Ashok Kumar”
      var = 25
      print(“name_1:”, name, “var:”, var)
      print(“name_2:”, name, “var:”,var)
      inner()
      print(“name_0:”, name, “inner:”, var)
      outer()
      print(“name_2:”, name, “inner:”, var)

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages