Everything about Python Namespace

In Python, a namespace is a system that organizes and identifies the names of objects such as variables, functions, classes, and modules in a program. Namespaces ensure that names are unique and can be easily located and accessed in a program.

Python has four main types of namespaces:

  1. Built-in namespace: This namespace contains the names of built-in functions, such as print() and len(), and built-in types, such as str and list.
  2. Global namespace: This namespace contains the names defined at the module level. These names can be accessed from anywhere within the module.
  3. Local namespace: This namespace contains the names defined inside a function or a block. These names can only be accessed within that function or block.
  4. Enclosed namespace: This namespace contains the names defined in the enclosing function of a nested function. These names can be accessed by the nested function.

Here is an example that demonstrates the use of namespaces:

# Define a variable in the global namespace
x = 10

def my_function():
    # Define a variable in the local namespace
    y = 20
    
    def nested_function():
        # Define a variable in the enclosed namespace
        z = 30
        
        # Access variables from all namespaces
        print(x)    # Access global variable x
        print(y)    # Access local variable y
        print(z)    # Access enclosed variable z
    
    nested_function()

my_function()

In the above example, x is defined in the global namespace, y is defined in the local namespace of my_function(), and z is defined in the enclosed namespace of nested_function(). The print() statements inside nested_function() demonstrate how variables can be accessed from all namespaces.

Leave a Reply