Sunday, June 12, 2022

Namespace And Variable Scope in Python

In this post we’ll see what is Namespace in Python and how different scopes are created as per the operating namespace.


What is name

To understand namespace in Python we’ll start first with what is name?

Here note that in Python numbers, strings, functions, lists etc. are all objects and name is a reference to the memory allocated to that object.

For example when you write num = 5 in Python, num is a name given to refer to the object having value 5.

namespace in python

Namespace in Python

Python namespace helps in ensuring that the names in any program are unique and those names can be used without any conflict.

Namespace in Python is implemented as a dictionary and it is a mapping from names to objects where name acts as a key and the object as a value. That way multiple namespaces may have variables with same names but those are mapped to different objects.

For example if there are two namespaces ns1 and ns2 where ns1 has attributes a and b where as ns2 has attributes a, b and c then the namespace dictionaries for these two namespaces can be depicted as-

ns1={a=obj1, b=obj2}
ns2={a=obj3, b=obj4, c=obj5}

Following Python example tries to clarify the concept of namespace.

class MyClass():
  # class variable in class namespace
  x = 10
  def my_method(self):
    # local namespace
    x = 12
    print("x(local)=", x)

obj1 = MyClass()
obj1.my_method()
# prints the class variable
print("x=", obj1.x)
obj2 = MyClass()
obj2.my_method()
print("x=", obj2.x)

Output

x(local)= 12
x= 10
x(local)= 12
x= 10

As you can see in the example there is a variable with the same name ‘x’ at the class level as well as with in a method. Since both are in different namespace so there is no conflict and both can be accessed as per their scope.

Types of namespaces in Python

In Python namespaces are created at different moments and have different lifetimes.

  1. Built-in namespace- This namespace contains the built-in functions and built-in exception names. Built-in namespace is created when the Python interpreter starts up, and is never deleted.
  2. Global namespace- This namespace contains the names in the modules that you import in your project. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits.
  3. Local namespace- This namespace contains names inside functions. The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function.

Scope in Python

A scope is a code region of a Python program where a namespace is directly accessible. Here directly accessible means that you don’t need to qualify reference to the name using object (i.e. obj.x) or class (i.e. MyClass.x) to find the name in the namespace. As per the available namespaces there are different scopes that can exist too.

  1. Local scope (or the innermost scope) contains the local names. This scope is searched first for any name.
  2. The scopes of any enclosing functions, which are searched starting with the nearest enclosing scope and moving outwards.
  3. Module level scope (next-to-last scope) contains the current module’s global names.
  4. The outermost scope is the namespace containing built-in name. This scope is searched last to find the name in the namespace.

As you can see scopes corresponds to the respective namespaces and names in the scopes are searched starting from innermost moving outwards.

Namespace and variable scope python

Python variable scope example

class MyClass():
  # class variable in class namespace
  x = 10
  def my_method(self):
    # local namespace
    x = 12
    def inner_method():
      x = 16
      print('x value inner', x)

    inner_method()
    print("x(local)=", x)

obj1 = MyClass()
obj1.my_method()
# prints the class variable
print("x=", obj1.x)

Output

x value inner 16
x(local)= 12
x= 10

In the example there is a global variable x with value as 10. There is a variable with the same name in function my_method with value as 12. There is a function inner_method with in the scope of my_method again having a variable x with the value as 16.

When this print statement print('x value inner', x) is executed the innermost scope is with in the method inner_method so the value of x is printed as 16.

When the statement print("x(local)=", x) is executed scope is with in the function my_method so the value of x is printed as 12.

That's all for this topic Namespace And Variable Scope in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Constructor in Python - __init__() function
  2. Class And Object in Python
  3. Interface in Python
  4. Inheritance in Python
  5. Method Overloading in Python

You may also like-

  1. Changing String Case in Python
  2. Python return Statement With Examples
  3. Python Program to Check Prime Number
  4. Comparing Two Strings in Python
  5. How to Sort ArrayList of Custom Objects in Java
  6. Deque Implementation in Java Using Doubly Linked List
  7. How to Inject Null And Empty String Values in Spring
  8. YARN in Hadoop

No comments:

Post a Comment