Python Namespace and scope – Get unique names for each object

In your school, college or office, confusion can arise because of people having the same names. This confusion is usually resolved by providing a unique identity like using first name and last name. The same problem can arise in programming also.

If you write a few lines of code then it is not a problem to assign unique names to every variable but when you load external modules and write thousands of lines of code then it is not possible to use unique and meaningful names for every object or variable. This is why namespaces are important and this article will be covering everything about Python namespace and scope.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is Python Namespace?

A namespace is a collection of names. Python implements namespaces as dictionaries. Imagine it as a name-to-object mapping where names are the keys and objects are the values. A namespace allows us to have unique names for each object. If you don’t know, this is just a quick reminder to tell you that strings, lists, functions, etc everything in Python is an object.

In simple words, we can say that the role of a namespace is like a surname. There can be multiple “Tom” in the same class but there will be a single “Tom Hanks” (let’s just assume this) in the class and with surname, you can identify between multiple “Tom”.

The Python interpreter does the same thing to understand what exact method or variable one is pointing to in the code. The namespace word itself can be broken down as name (which is a unique identifier) + space (which means relating to scope). The name can be anything from method name to variable name and space depends upon the location from where we are trying to access a variable or a method.

Time to get familiar with TechVidvan’s Python Variables.

Types of Namespaces in PythonPython namespace types

Namespaces are of basically three types:

1. Built-in Namespace

This namespace includes functions and exception names that are built-in in the Python.

2. Global Namespace

This namespace includes names from the modules that are imported in the project. It is created when we include the module and it lasts until the script ends.

3. Local Namespace

The local names inside the function comes under a local namespace. This namespace is created when the function is called and the scope ends when the value is returned.

Python Scope

With namespaces, we can uniquely identify all the names inside a program. However, it doesn’t mean that we can use the variable names anywhere we want. It also has some scope that indicates the part of the program where we can access them. We can directly access the variables without any prefix when they are in the namespace.

The lifetime of a namespace is dependent on the scope of objects. When the scope of an object comes to end, the lifetime of the namespace also comes to an end. So, we cannot access the inner namespace scope’s objects from an outer namespace.

Python has the following scopes –python scope types

When a name is referenced in Python, the interpreter searches the name in the namespace starting from the smallest scope in the diagram and gradually moves towards the outermost scope.

  • The local scope, which is the innermost scope contains a list of local names that are only available in the function.
  • Enclosing scopes are seen in nested functions where names are searched in the nearest outside function.
  • The global scope is the module-level scope. When we import modules, they get added to the global scope.
  • The outermost scope is of the built-in names scope. The interpreter searches names in this scope at last.

Time to check out the Variables Scope in Python.

Example of Namespaces and Scope

Now, we will see some examples of namespaces and scope –

Example 1

#var1 is in the global namespace
var1 = 5
def function():

    # var2 is in the local namespace
    var2 = 6
    def inner_function():

        # var3 is in the nested local
        # namespace
        var3 = 7

In this example, the var1 is declared in the global namespace because it is not enclosed inside any function. So it is accessible everywhere in the script.

var2 is inside the function(). So, it can be accessed only inside the function() and outside the function, it no longer exists.

var3 also has a local scope, the function is nested and we can use var3 only inside inner_function().

In the next example, try yourself what should be the output of the following code and then look at the output.

Example 2

Code:

var = "10"
def example():
  var = "30"
  def method():
    global var
    var = "40"
    def function():
      global var
      var = "50"
      print("Function Scope: " + var)
    function()
    print("Method Scope: " + var)
  method()
  print("Example Scope: " + var)
example()
print("Module Scope: " + var)

Output:

Function Scope: 50
Method Scope: 50
Example Scope: 30
Module Scope: 50

Let’s break down how we got the following output –

In the global scope first, we declared the variable ‘var’ and initialized it with value = 10.

In the example() function, we declare a local variable ‘var’ =30. Since they are declared in different namespaces, we can have variables with the same names in different scopes.

The global keyword is used to indicate that we are referencing the global variable in this scope that is why in function() the value now holds 50. Same as method() function and the example() function is holding the local variable whose value is 30 and in the end, the last value of the global variable was 50.

Summary

In this article, we studied about the namespaces and scope in Python. They are necessary to solve the problem of conflicting names while naming objects. We saw the different types of namespaces (built-in, global and local) and scopes. Further on, we saw easy examples of namespaces and scope.

If you liked TechVidvan’s Python namespace and scope article, do share it with your friends on social media.

1 Response

  1. Mahendar says:

    print(“Module Scope: ” + var)

    That should be 10. The output you got is 50.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.